-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy path01-StackWeakMap.js
70 lines (60 loc) · 1.24 KB
/
01-StackWeakMap.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
59
60
61
62
63
64
65
66
67
68
69
70
// @ts-check
const _items = new WeakMap();
const _count = 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;
}
size() {
return _count.get(this);
}
clear() {
/* while (!this.isEmpty()) {
this.pop();
} */
_count.set(this, 0);
_items.set(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;
}
}