-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSets.js
96 lines (86 loc) · 2.32 KB
/
Sets.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
87
88
89
90
91
92
93
94
95
96
/** Sets */
function mySet() {
// the var collection will hold the set
const collection = []
// this method will check for the presence of an element and return truw or false
this.has = function(element) {
return (collection.indexOf(element) !== -1)
}
// this method will return all the values in the set
this.values = function() {
return collection
}
// this method will add an element to the set
this.add = function(element) {
if(!this.has(element)) {
collection.push(element)
return true
}
return false
}
// this method will remove an element from a set
this.remove = function(element) {
if(this.has(element)) {
const index = collection.indexOf(element)
collection.splice(index, 1)
return true
}
return false
}
// this method will return the size of the collection
this.size = function() {
return collection.length
}
// this method will return the union of two sets
this.union = function(otherSet) {
var unionSet = new mySet()
var firstSet = this.values();
var secondSet = otherSet.values()
firstSet.forEach(function(e) {
unionSet.add(e)
})
secondSet.forEach(function(e) {
unionSet.add(e)
})
return unionSet
}
// this method will return the intersection of two sets as a new set
this.intersection = function(otherSet) {
var intersectionSet = new mySet()
var firstSet = this.values()
firstSet.forEach(function(e) {
if (otherSet.has(e)) {
intersectionSet.add(e)
}
})
return intersectionSet
}
// this method will return the difference of two sets as a new set
this.difference = function(otherSet) {
var differenceSet = new mySet()
var firstSet = this.values()
firstSet.forEach(function(e) {
if(!otherSet.has(e)) {
differenceSet.add(e)
}
})
return differenceSet
}
// this method will test if the set is a subset of a different set
this.subset = function(otherSet) {
var firstSet = this.values()
return firstSet.every(function(value) {
return otherSet.has(value)
})
}
}
var setA = new mySet()
var setB = new mySet()
setA.add("a")
setB.add("b")
setB.add("c")
setB.add("a")
setB.add("d")
console.log(setA.subset(setB))
console.log(setA.intersection(setB).values())
console.log(setB.difference(setA).values())