forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalanced-symbols.ts
43 lines (41 loc) · 1.18 KB
/
balanced-symbols.ts
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
42
43
import Stack from '../data-structures/stack';
export function parenthesesChecker(symbols: string) {
const stack = new Stack<string>();
const opens = '([{';
const closers = ')]}';
let balanced = true;
let index = 0;
let symbol: string;
let top: string;
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;
}