-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathstack-weakMap.js
More file actions
106 lines (89 loc) · 1.92 KB
/
Copy pathstack-weakMap.js
File metadata and controls
106 lines (89 loc) · 1.92 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// // 数组
// const items = new WeakMap()
// class Stack {
// constructor() {
// items.set(this, [])
// }
// /** 入栈 */
// push(element) {
// const temp = items.get(this)
// temp.push(element)
// }
// /** 出栈 */
// pop() {
// const temp = items.get(this)
// const temp2 = temp.pop()
// return temp2
// }
// /**
// * 剩下的方法都是这个规则
// */
// }
const _count = new WeakMap()
const _items = new WeakMap()
class Stack {
constructor() {
_count.set(this, 0)
_items.set(this, {})
}
/** 入栈 */
push(element) {
const items = _items.get(this)
const count = _count.get(this)
items[count] = element
_count.set(this, count + 1)
}
/** 出栈 */
pop() {
if (this.isEmpty()) return undefined
const items = _items.get(this)
let count = _count.get(this)
count--
_count.set(this, count)
const result = items[count]
delete items[count]
return result
}
/** 栈顶元素 */
peek() {
if (this.isEmpty()) return undefined
const items = _items.get(this);
const count = _count.get(this);
return items[count - 1];
}
/** 栈是否为空 */
isEmpty() {
return _count.get(this) === 0;
}
/** 清空栈 */
clear() {
_count.set(this, 0);
_items.set(this, {});
// 或则遵守LIFO原则
// while (!this.isEmpty()) {
// this.pop()
// }
}
/** 栈长 */
size() {
return _count.get(this);
}
/** 拓展-输出当前栈 */
toString() {
if (this.isEmpty()) return ''
const items = _items.get(this);
const count = _count.get(this);
let objString = `${items[0]}`;
for (let i = 1; i < count; i++) {
objString = `${objString},${items[i]}`;
}
return objString;
}
}
// test
const xxx = new Stack()
xxx.push(3)
xxx.push(2)
console.log('pop = ', xxx.pop());
console.log('peek = ', xxx.peek());
console.log('toString = ', xxx.toString());