forked from tzeikob/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
58 lines (43 loc) · 953 Bytes
/
index.js
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
// Use your own namespace to keep global scope clean
var myNS = myNS || Object.create(null);
myNS.Stack = function() {
// Use weak map to encapsulate the items of each stack instance
let data = new WeakMap();
class Stack {
constructor() {
// User an array to store the items
data.set(this, []);
}
push(item) {
data.get(this).push(item);
return this.size();
}
pop() {
return data.get(this).pop();
}
peek() {
let size = this.size();
return data.get(this)[size - 1];
}
isEmpty() {
return this.size() === 0;
}
clear() {
data.set(this, []);
}
size() {
return data.get(this).length;
}
toString() {
return `Stack: [${data.get(this).join(', ')}]`;
}
}
return Stack;
}();
let s = new myNS.Stack();
s.push(3); // [3]
s.push(9); // [3, 9]
s.push(6); // [3, 9, 6]
s.pop(); // 6
s.peek(); // 9
s.clear(); // []