Created
February 28, 2018 14:51
-
-
Save jonurry/40c3f2fe4952f455d1194a4eb68c70c2 to your computer and use it in GitHub Desktop.
6.2 Groups (Eloquent JavaScript Solutions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Group { | |
constructor() { | |
this.group = []; | |
} | |
add(item) { | |
if (!this.group.includes(item)) { | |
this.group.push(item); | |
} | |
} | |
delete(item) { | |
let index = this.group.indexOf(item); | |
if (index !== -1) { | |
this.group.splice(index, 1); | |
} | |
} | |
has(item) { | |
return this.group.includes(item); | |
} | |
static from(a) { | |
let g = new Group(); | |
for (let item of a) { | |
g.add(item); | |
} | |
return g; | |
} | |
} | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hints
The easiest way to do this is to store an array of group members in an instance property. The
includes
orindexOf
methods can be used to check whether a given value is in the array.Your class’ constructor can set the member collection to an empty array. When
add
is called, it must check whether the given value is in the array, and add it, for example withpush
, otherwise.Deleting an element from an array, in
delete
, is less straightforward, but you can usefilter
to create a new array without the value. Don’t forget to overwrite the property holding the members with the newly filtered version of the array.The
from
method can use afor/of
loop to get the values out of the iterable object, and calladd
to put them into a newly created group.