Created
January 29, 2016 03:25
-
-
Save timothyjoh/6f52ff990552a62b43fe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var _ = require('lodash'); | |
// allow for parenthesis square brackets, curly braces | |
function check(input) { | |
var tokens = [[/\[/,/\]/],[/\{/,/\}/],[/\(/, /\)/]]; | |
/* | |
search for the token pair on a string, starting with input | |
*/ | |
var searchInput = function(pair) { | |
return searchPair(pair,input); | |
}; | |
/* | |
search for the token pair on a string, recursively | |
*/ | |
var searchPair = function(pair, str) { | |
if (str === '') return true; // no more string to search, return true | |
var matchFirst = searchToken(pair[0],str); | |
if (matchFirst.length > 0) { | |
var matchSecond = searchToken(pair[1],matchFirst); | |
if (matchSecond.length == 0) { | |
return false; | |
} | |
} | |
// recursively call this function as long as there is more | |
return searchPair(pair,matchFirst); | |
}; | |
/* | |
search for the given token and return the remaining string after the token | |
*/ | |
var searchToken = function(token, str) { | |
if (str.search(token) > -1) { | |
return str.substring(str.search(token) +1); | |
} else { | |
return ''; | |
} | |
}; | |
console.log("Validating input: "+input); | |
// _.map(tokens, searchInput) will return us an array | |
// with a true or false for each token | |
// adding the _.compact is just a way to say if any of the array are false | |
// then the whole check is false | |
return _.compact(_.map(tokens, searchInput)).length === tokens.length; | |
} | |
console.log(check("sdsf[wer")); // short and false | |
console.log(check("sdkskdjf(sd[sd]f)sdfs{df(wesdf)sd}fsd(sdfsd(sdfssdf)sdzs)")); // long and good | |
console.log(check("sdkskdjf(sd[sd]f)sdfs{df(wesdf)sd}fsd(sdfsd(sdfssdf)sd[zs)")); // long and false (at the end, an open [ bracket) | |
/* --- my ouput | |
Sites/viv $ node app.js | |
Validating input: sdsf[wer | |
false | |
Validating input: sdkskdjf(sd[sd]f)sdfs{df(wesdf)sd}fsd(sdfsd(sdfssdf)sdzs) | |
true | |
Validating input: sdkskdjf(sd[sd]f)sdfs{df(wesdf)sd}fsd(sdfsd(sdfssdf)sd[zs) | |
false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment