Advertisement
Guest User

Untitled

a guest
May 28th, 2015
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. function balancedPars(str) {
  2. var result = 0;
  3.  
  4. if(typeof(str) !== 'string') return false;
  5.  
  6. if(str) {
  7. result = str.split('')
  8. .map(function(elem){
  9. return elem === '(' ? 1 : (elem === ')' ? -1 : 0);
  10. })
  11. .reduce(function(prev, curr, index, arr){
  12. return prev < 0 ? prev : prev + curr;
  13. });
  14. }
  15.  
  16. return result === 0;
  17. }
  18.  
  19. // Test it!
  20. assert(balancedPars, true, '()');
  21. assert(balancedPars, false, ')(');
  22. assert(balancedPars, true, '');
  23. assert(balancedPars, false, '(()');
  24. assert(balancedPars, false, '())');
  25. assert(balancedPars, true, '(())()()');
  26. assert(balancedPars, false, 123);
  27. assert(balancedPars, true, '(a + (b - c) * d)');
  28.  
  29. // Assert Help Function
  30. function assert(fn, expected, args) {
  31. var args = [].slice.call(arguments, 2),
  32. fnName = fn.toString().replace('function ', '').split('(')[0],
  33. message = 'Test: ' + fnName + ' : ' + args.join(', ') + ' => ',
  34. result = fn.apply(this, args);
  35.  
  36. if(result == expected) {
  37. console.log(message + 'OK');
  38. } else {
  39. console.error(message + 'Assertion error. Expected: ', expected, 'Got: ', result);
  40. }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement