-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.object.js
More file actions
52 lines (42 loc) · 1.01 KB
/
stack.object.js
File metadata and controls
52 lines (42 loc) · 1.01 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
class Stack {
constructor() {
this._storage = {};
this._size = 0;
}
push(data) {
this._size++;
this._storage[this._size] = data;
}
pop() {
if (this._size) {
let deletedData = this._storage[this._size];
delete this._storage[this._size];
this._size--;
return deletedData;
}
}
size() {
return this._size;
}
peek() {
return this._storage[this._size];
}
print() {
console.log(this._storage);
}
}
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.print(); // => { '1': 1, '2': 2, '3': 3 }
console.log('size is 3:', stack.size()); // => 3
console.log('peek is 3:', stack.peek()); // => 3
console.log('pop is 3:', stack.pop()); // => 3
stack.print(); // => { '1': 1, '2': 2 }
console.log('peek is 2:', stack.peek()); // => 2
console.log('pop is 2:', stack.pop()); // => 2
console.log('size is 1:', stack.size()); // => 1
console.log('pop is 1:', stack.pop()); // => 1
stack.print(); // => '{}'
console.log('pop is undefined:', stack.pop()); // => undefined