forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03-BalancedSymbols.js
41 lines (38 loc) · 1.33 KB
/
03-BalancedSymbols.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
function parenthesesChecker(symbols){
let stack = new Stack(),
balanced = true,
index = 0,
symbol, top,
opens = "([{",
closers = ")]}";
while (index < symbols.length && balanced){
symbol = symbols.charAt(index);
if (opens.indexOf(symbol) >= 0){
stack.push(symbol);
console.log(`open symbol - stacking ${symbol}`);
} else {
console.log(`close symbol ${symbol}`);
if (stack.isEmpty()){
balanced = false;
console.log('Stack is empty, no more symbols to pop and compare');
} else {
top = stack.pop();
//if (!matches(top, symbol)){
if (!(opens.indexOf(top) === closers.indexOf(symbol))) {
balanced = false;
console.log(`poping symbol ${top} - is not a match compared to ${symbol}`);
} else {
console.log(`poping symbol ${top} - is is a match compared to ${symbol}`);
}
}
}
index++;
}
if (balanced && stack.isEmpty()){
return true;
}
return false;
}
console.log(parenthesesChecker('{([])}')); //true
console.log(parenthesesChecker('{{([][])}()}')); //true
console.log(parenthesesChecker('[{()]')); //false