-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSets.js
116 lines (92 loc) · 2.67 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/* Sets */
class mySet {
constructor() {
// the collection will hold the set
this.collection = [];
}
// this method will check for the presence of an element and return true or false
has(ele) {
return (this.collection.indexOf(ele) !== -1);
}
// this.method will return all the values in the set
values() {
return this.collection;
}
// this method will add an element to the Set
add(...ele) {
for (let item of ele) {
if(!this.has(item)) {
this.collection.push(item);
}
}
}
// this method will remove an element from a set
remove(ele) {
if(this.has(ele)) {
let index = this.collection.indexOf(ele);
this.collection.splice(index, 1);
return true;
}
return false;
}
// this method will return the size of the collection
size() {
return this.collection.length;
}
// this method will return the union of two Sets
union(otherSet) {
let unionSet = new mySet();
let firstSet = this.values();
let secondSet = otherSet.values();
firstSet.forEach(e=>{
unionSet.add(e);
});
secondSet.forEach(e=>{
unionSet.add(e);
});
return unionSet;
}
//this method will return the intersection of two sets as a new set
intersection(otherSet) {
let intersection = new mySet();
let firstSet = this.values();
firstSet.forEach(e=>{
if(otherSet.has(e)) {
intersection.add(e);
}
});
return intersection;
}
// this method will return the difference of two sets as a new set
difference(otherSet) {
let differenceSet = new mySet();
let firstSet = this.values();
firstSet.forEach(e=>{
if(!otherSet.has(e)) {
differenceSet.add(e);
}
});
return differenceSet;
}
// this method will test if the set is a subset of a difference set
subset(otherSet) {
let firstSet = this.values();
return firstSet.every(e=>{
return otherSet.has(e);
});
}
}
let setA = new mySet();
let setB = new mySet();
setA.add('a');
setB.add('b', 'c', 'a', 'd');
console.log(setA.subset(setB)); // true
console.log(setA.intersection(setB).values()); // ['a']
console.log(setB.difference(setA).values()); //[ 'b', 'c', 'd' ]
let setC = new mySet();
let setD = new mySet();
setC.add('a');
setD.add('b', 'c', 'a', 'd');
console.log(setD.values()); //[ 'b', 'c', 'a', 'd' ]
setD.remove('a');
console.log(setD.has('a'));