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

6.2 Groups

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 only be part of a set 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 the argument and creates a group that contains all the values produced by iterating over it.

@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