Skip to content

Instantly share code, notes, and snippets.

@sheniff
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save sheniff/1613995c3ae5f34746c4 to your computer and use it in GitHub Desktop.

Select an option

Save sheniff/1613995c3ae5f34746c4 to your computer and use it in GitHub Desktop.
I wanted to try solving parenthesis balance checking using map-reduce approach in JS :)
function balancedPars(str) {
var result = 0;
if(typeof(str) !== 'string') return false;
if(str) {
result = str.split('')
.map(function(elem){
return elem === '(' ? 1 : (elem === ')' ? -1 : 0);
})
.reduce(function(prev, curr, index, arr){
return prev < 0 ? prev : prev + curr;
});
}
return result === 0;
}
// Test it!
assert(balancedPars, true, '()');
assert(balancedPars, false, ')(');
assert(balancedPars, true, '');
assert(balancedPars, false, '(()');
assert(balancedPars, false, '())');
assert(balancedPars, true, '(())()()');
assert(balancedPars, false, 123);
assert(balancedPars, true, '(a + (b - c) * d)');
// Assert Help Function
function assert(fn, expected, args) {
var args = [].slice.call(arguments, 2),
fnName = fn.toString().replace('function ', '').split('(')[0],
message = 'Test: ' + fnName + ' : ' + args.join(', ') + ' => ',
result = fn.apply(this, args);
if(result == expected) {
console.log(message + 'OK');
} else {
console.error(message + 'Assertion error. Expected: ', expected, 'Got: ', result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment