I'm trying to understand how stacks are working through code. Now, I tried to write a simple bracket-matching program: I've wrote linked list implementation and I've used it to implement stack in JS. The idea is in iterating through all characters in string and putting open-brackets in stack. After this, if there is no matching bracket for the top-bracket, function should return false. The main problem is, that if-statement executes everything but return-statement in it.
Input: ([(a()]])
Desired output: false
function isBalanced(string) {
let stack = new Stack();
[...string].forEach(char => {
let bracket
if (char === '[' || char === '(') {
stack.push(char)
} else {
if (stack.isEmpty()) {
return false
}
bracket = stack.pop().data
console.log(`PAIR: ${bracket}${char}`)
if (!(bracket === "[" && char === "]") && !(bracket === "(" && char === ")")) {
console.log("working")
return false
}
}});
return stack.isEmpty();
}
let string = '([(a()]])'
console.log(isBalanced(string))
I've used console.log()
to check if my statement works and on which pairs does it work.
Output in console looks like this:
PAIR: (a
working
PAIR: ()
PAIR: []
PAIR: (]
working
true
As you can see, when statement is true, it's definitely work, but it doesn't call the inner return-statement (after first 'working'
output, there should be no more pairs in console; just false
). Where is the problem?
CodePudding user response:
You could use Array#every
along with the length check of the stack and return inside of the callback for every right character true
.
function isBalanced(string) {
const
closed = { '(': ')', '[': ']' },
stack = [];
return [...string].every(char => {
if (char === '[' || char === '(') {
stack.push(char);
return true;
}
if (!stack.length) return false;
const bracket = stack.pop();
console.log(`PAIR: ${bracket}${char}`);
return closed[bracket] === char;
}) && !stack.length;
}
console.log(isBalanced('(([()]))'));
console.log(isBalanced('([(a()]])'));
.as-console-wrapper { max-height: 100% !important; top: 0; }