forked from tzeikob/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
85 lines (62 loc) · 1.36 KB
/
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
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
// Use your own namespace to keep global scope clean
var myNS = myNS || Object.create(null);
myNS.Set = function() {
// Use weak map to encapsulate the items of each set instance
const data = new WeakMap();
class Set {
constructor() {
// Use an array to store the items
data.set(this, []);
}
add(item) {
if (this.has(item)) {
return false;
}
data.get(this).push(item);
return true;
}
remove(item) {
if (!this.has(item)) {
return false;
}
let values = data.get(this);
// Splice array item to free up space
let index = values.indexOf(item);
values.splice(index, 1);
return true;
}
has(item) {
return data.get(this).indexOf(item) !== -1;
}
isEmpty() {
return this.size() === 0;
}
clear() {
data.set(this, []);
}
size() {
return data.get(this).length;
}
values() {
return data.get(this);
}
toString() {
return `Set: [${data.get(this).join(', ')}]`;
}
}
return Set;
}();
let s = new myNS.Set();
let o1 = {
id: 1,
name: "Bob"
};
let o2 = {
id: 2,
name: "Alice"
};
s.add(o1); // [{id: 1, name: "Bob"}]
s.add(o1); // [{id: 1, name: "Bob"}]
s.add(o2); // [{id: 1, name: "Bob"}, {id: 2, name: "Alice"}]
s.remove(o1); // [{id: 2, name: "Alice"}]
s.clear(); // []