-
Notifications
You must be signed in to change notification settings - Fork 0
/
has.js
87 lines (79 loc) · 2.51 KB
/
has.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
/* Perform a Difference on Two Sets of Data
In this exercise we are going to perform a difference on 2 sets of data. We will create a method on our Set data structure called difference. A difference of sets should compare two sets and return the items present in the first set that are absent in the second. This method should take another Set as an argument and return the difference of the two sets.
For example, if setA = ['a','b','c'] and setB = ['a','b','d','e'], then the difference of setA and setB is: setA.difference(setB) = ['c'].*/
class Set {
constructor() {
// This will hold the set
this.dictionary = {};
this.length = 0;
}
// This method will check for the presence of an element and return true or false
has(element) {
return this.dictionary[element] !== undefined;
}
// This method will return all the values in the set
values() {
return Object.keys(this.dictionary);
}
// This method will add an element to the set
add(element) {
if (!this.has(element)) {
this.dictionary[element] = true;
this.length++;
return true;
}
return false;
}
// This method will remove an element from a set
remove(element) {
if (this.has(element)) {
delete this.dictionary[element];
this.length--;
return true;
}
return false;
}
// This method will return the size of the set
size() {
return this.length;
}
// This is our union method
union(set) {
const newSet = new Set();
this.values().forEach(value => {
newSet.add(value);
})
set.values().forEach(value => {
newSet.add(value);
})
return newSet;
}
// This is our intersection method
intersection(set) {
const newSet = new Set();
let largeSet;
let smallSet;
if (this.dictionary.length > set.length) {
largeSet = this;
smallSet = set;
} else {
largeSet = set;
smallSet = this;
}
smallSet.values().forEach(value => {
if (largeSet.dictionary[value]) {
newSet.add(value);
}
})
return newSet;
}
// Only change code below this line
difference(anotherSet){
let newSet = new Set();
this.values().forEach(value => {
// if (!anotherSet.values().includes(value)) // use includes on set.values() to see if it is in that array
})
return newSet;
}
// Only change code above this line
}