-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharrayStack.js
More file actions
41 lines (33 loc) · 773 Bytes
/
arrayStack.js
File metadata and controls
41 lines (33 loc) · 773 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
// Array Stack
const _stack = new WeakMap();
class Stack {
constructor(...arr) {
_stack.set(this, arr);
}
push(...val) {
const stack = _stack.get(this);
if (!val || !val.toString().trim()) throw new Error(`Invalid value`);
stack.push(...val);
_stack.set(this, stack);
}
pop() {
const stack = _stack.get(this);
if (!stack.length) throw new Error(`Stack is Empty`);
stack.pop();
_stack.set(this, stack);
}
peek() {
const stack = _stack.get(this);
if (!stack.length) throw new Error(`Stack is Empty`);
return stack[stack.length - 1];
}
get length() {
return _stack.get(this).length;
}
}
const stack = new Stack();
stack.push(1, 2, 1);
stack.pop();
stack.peek();
stack.length;
console.log(stack);