Repository navigation
Expand file tree
/
Copy pathstack.ts
More file actions
59 lines (51 loc) · 1.53 KB
/
Copy pathstack.ts
File metadata and controls
59 lines (51 loc) · 1.53 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* Stack (last in, first out)
*
* Idea: you can only touch the top. `push` puts a value on top, `pop` takes
* the top value off. A JavaScript array already grows at the end in amortized
* constant time, so the stack is a thin, intention-revealing wrapper.
*
* Used for: undo history, matching brackets, depth-first search without
* recursion, evaluating expressions, and the call stack itself.
*
* Complexity: push / pop / peek are O(1) amortized; space O(n).
*/
export class Stack<T> implements Iterable<T> {
private items: T[] = [];
get size(): number {
return this.items.length;
}
isEmpty(): boolean {
return this.items.length === 0;
}
push(value: T): this {
this.items.push(value);
return this;
}
pop(): T | undefined {
return this.items.pop();
}
peek(): T | undefined {
return this.items[this.items.length - 1];
}
/** Values from top to bottom. */
toArray(): T[] {
return [...this.items].reverse();
}
*[Symbol.iterator](): Iterator<T> {
for (let i = this.items.length - 1; i >= 0; i--) yield this.items[i] as T;
}
}
/** Classic stack exercise: are all (), [] and {} balanced and properly nested? */
export function isBalanced(text: string): boolean {
const pairs: Record<string, string> = { ")": "(", "]": "[", "}": "{" };
const stack = new Stack<string>();
for (const ch of text) {
if (ch === "(" || ch === "[" || ch === "{") {
stack.push(ch);
} else if (ch in pairs) {
if (stack.pop() !== pairs[ch]) return false;
}
}
return stack.isEmpty();
}