This repository has been archived by the owner on Mar 29, 2020. It is now read-only.
/
groups.js
60 lines (47 loc) · 1.85 KB
/
groups.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
/*
2 - Groups (6/1/2019)
The standard JavaScript environment provides another data structure called Set. Like an instance of Map, a set holds a collection of values. Unlike Map, it does not associate other values with those—it just tracks which values are part of the set. A value can be part of a set only once—adding it again doesn’t have any effect.
Write a class called Group (since Set is already taken). Like Set, it has add, delete, and has methods. Its constructor creates an empty group, add adds a value to the group (but only if it isn’t already a member), delete removes its argument from the group (if it was a member), and has returns a Boolean value indicating whether its argument is a member of the group.
Use the === operator, or something equivalent such as indexOf, to determine whether two values are the same.
Give the class a static from method that takes an iterable object as argument and creates a group that contains all the values produced by iterating over it.
*/
class Group {
constructor() {
this.group = [];
}
add(value) {
if (!this.has(value)) {
this.group.push(value);
}
}
delete(value) {
if (this.has(value)) {
const removeDelete = this.group.indexOf(value);
delete this.group[removeDelete];
}
}
has(value) {
for (let member of this.group) {
if (member === value) {
return true;
}
}
return false;
}
static from(iterable) {
let group = new Group();
for (let element of iterable) {
group.add(element);
}
return group;
}
}
let group = Group.from([10, 20]);
console.log(group.has(10));
// → true
console.log(group.has(30));
// → false
group.add(10);
group.delete(10);
console.log(group.has(10));
// → false