Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. /**
  2. * Tests if the brackets in a given string are balanced
  3. * @param {string} expression - the expression string to be tested.
  4. */
  5. function areBracketsBalanced(expression) {
  6. if (!expression) {
  7. return false;
  8. }
  9.  
  10. /**
  11. * @type {Array} stack
  12. */
  13. const stack = [];
  14.  
  15. const arePairing = (opening, closing) =>
  16. (opening == "(" && closing == ")") ||
  17. (opening == "{" && closing == "}") ||
  18. (opening == "[" && closing == "]");
  19.  
  20. const isOpening = char => char == "(" || char == "[" || char == "{";
  21. const isClosing = char => char == ")" || char == "]" || char == "}";
  22.  
  23. [...expression].forEach(char => {
  24. if (isOpening(char)) {
  25. stack.push(char);
  26. } else if (isClosing(char)) {
  27. // assures that closures are occuring in the correct order.
  28. if (!stack.length || !arePairing(stack[stack.length - 1], char)) {
  29. return false;
  30. } else {
  31. stack.pop();
  32. }
  33. }
  34. });
  35.  
  36. return !stack.length;
  37. }
  38.  
  39. // Test cases
  40. console.log(Solution("(a[0]+b[2c[6]]){24+53}"));
  41. console.log(Solution("f(e(d))"));
  42. console.log(Solution("[()]{}([])"));
  43. console.log(Solution("((b)"));
  44. console.log(Solution("(c]"));
  45. console.log(Solution("{(a[])"));
  46. console.log(Solution("([(]"));
  47. console.log(Solution(")("));
  48. console.log(Solution(""));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement