6
\$\begingroup\$

I am currently refining my understanding of data structures and as such, decided to implement a popular application of the Stack. Below you will find my implementation of the Balancing Symbols algorithm written in JavaScript.

My basic questions are:

  • How clean would you rate my code?
  • Is time complexity O(n): Linear?
  • How can I improve?
function isBalanced(arr){
  var stack = new Stack();
  var last;

  arr.forEach(function(curr){
    if (curr === '(' || curr === '[' || curr === '{') {
      stack.push(curr);
    }

    if (curr === ')' || curr === ']' || curr === '}') {
      last = stack.peek() + curr;
      if (last === '()' || last === '[]' || last === '{}') {
        stack.pop();
      }
    }
  });

  var result = (stack.length() === 0) ?  true : false;
  console.log(result);
}

var symbols = ['{', '(', ')', ']'];

isBalanced(symbols);
\$\endgroup\$
2
\$\begingroup\$

The code looks reasonably clean, IMO. I assume that it is purposely ES5?

I don't know about Stack as it's not a ES5 standard API (that I know of).

You are not returning any value. There is no need for ? true : false — just do return stack.length() === 0;.

Some code that you can consider, in ES5.

var completes = ['()', '[]', '{}'];
var open = completes.map(function(complete) {
  return complete.charAt(0);
});
var close = completes.map(function(complete) {
  return complete.charAt(1);
});

function isBalanced(arr) {
  var stack = [];
  arr.forEach(function(curr) {
    if (open.indexOf(curr) !== -1) {
      stack.push(curr);
    }
    if (close.indexOf(curr) !== -1) {
      var last = stack.pop();
      if (completes.indexOf(last + curr) === -1) {
        stack.push(last);
      }
    }
  });
  return stack.length === 0;
}

console.log(isBalanced(['{', '(', ')', ']']));
console.log(isBalanced(['[', '(', ')', ']']));

\$\endgroup\$
  • \$\begingroup\$ Yes it is ES5 on purpose, I just wanted to get the concepts down rather than config my environment to execute ES6. Stack was a class that I created to mimic the functionality from other OOP languages. \$\endgroup\$ – Pazuzu Sep 18 '16 at 0:41
  • \$\begingroup\$ I assume that Stack is pretty similar in functionality as the code in my example? \$\endgroup\$ – Xotic750 Sep 18 '16 at 0:50
  • \$\begingroup\$ Yes, arrays in JS have almost identical functionality to the methods in my Stack class. You're solid. \$\endgroup\$ – Pazuzu Sep 18 '16 at 0:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.