Skip to content

Instantly share code, notes, and snippets.

@jonurry
Created February 28, 2018 14:51
Show Gist options
  • Save jonurry/40c3f2fe4952f455d1194a4eb68c70c2 to your computer and use it in GitHub Desktop.
Save jonurry/40c3f2fe4952f455d1194a4eb68c70c2 to your computer and use it in GitHub Desktop.
6.2 Groups (Eloquent JavaScript Solutions)
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
@jonurry
Copy link
Author

jonurry commented Feb 28, 2018

Hints

The easiest way to do this is to store an array of group members in an instance property. The includes or indexOf 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 with push, otherwise.

Deleting an element from an array, in delete, is less straightforward, but you can use filter 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 a for/of loop to get the values out of the iterable object, and call add to put them into a newly created group.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment