Skip to main content
edited tags; edited title
Link
Jamal
  • 35.2k
  • 13
  • 134
  • 238

Can this code be optimized with features from ES6? Checking if parentheses are balanced

Source Link

Can this code be optimized with features from ES6?

This script checks if parentheses are balanced. I wonder if there is something that can be improved here including ES6 features.

function isBalanced(str) {
    var stack = [];
    const allowedSymbols = '()[]<>';

    for(let i = 0, l = str.length; i < l; i++) {
        var c = str[i];
        var isOpen;
        var symbolPosition = allowedSymbols.indexOf(c);

        if(!~symbolPosition) {
            continue;
        }

        isOpen = symbolPosition % 2 ? false : true;

        if(isOpen) {
            stack.push(c);
        } else {
            if(stack.length < 1 || allowedSymbols.indexOf(stack.pop()) !== symbolPosition - 1) {
                return false;
            }
        }
    }

    return stack.length < 1;
}

console.log('()', isBalanced('()')); //true
console.log(')(', isBalanced(')(')); //false