Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement