-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.ts
More file actions
41 lines (32 loc) · 811 Bytes
/
stack.ts
File metadata and controls
41 lines (32 loc) · 811 Bytes
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
export interface Stack<T> {
length: number;
pop: () => [Stack<T>, T | undefined];
push: (element: T) => Stack<T>;
toArray: () => T[];
top?: T;
}
export function Stack<T>(...elements: T[]) {
const stackElements = Object.freeze(elements);
const stack: Stack<T> = {
get length() {
return stackElements.length;
},
pop() {
const updatedElements = [...elements];
const removedElement = updatedElements.pop();
return [Stack(...updatedElements), removedElement];
},
push(element) {
const updatedElements = [...stackElements];
updatedElements.push(element);
return Stack(...updatedElements);
},
toArray() {
return [...stackElements];
},
get top() {
return stackElements.at(-1);
}
};
return stack;
}