-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset.js
86 lines (68 loc) · 1.64 KB
/
set.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
86
// implements [values] [size] [has] [add] [remove] [union] [intersection] [difference] [subset]
function MySet() {
const collection = []
this.has = function(element) {
return collection.indexOf(element) !== -1
}
this.values = function() {
return collection
}
this.size = function() {
return collection.length
}
this.add = function(element) {
if (!this.has(element)) {
collection.push(element)
return true
} else {
return false
}
}
this.remove = function(element) {
if (this.has(element)) {
const index = collection.indexOf(element)
collection.splice(index, 1)
return true
} else {
return false
}
}
this.union = function(otherSet) {
const unionSet = MySet()
const firstSet = this.values()
const secondSet = otherSet.values()
firstSet.forEach(function(e) {
unionSet.add(e)
})
secondSet.forEach(function(e) {
unionSet.add(e)
})
return unionSet
}
this.intersection = function(otherSet) {
const intersectionSet = new MySet()
const firstSet = this.values()
firstSet.forEach(function(e) {
if (otherSet.has(e)) {
intersectionSet.add(e)
}
})
return intersectionSet
}
this.difference = function(otherSet) {
const differenceSet = new MySet()
const firstSet = this.values()
firstSet.forEach(function(e) {
if (!otherSet.has(e)) {
differenceSet.add(e)
}
})
return differenceSet
}
this.subset = function(otherSet) {
const firstSet = this.values()
return firstSet.every(function(value) {
return otherSet.has(value)
})
}
}