Created
March 15, 2018 11:41
-
-
Save jonurry/3445e23c69b70201bf2a313f653bda27 to your computer and use it in GitHub Desktop.
7.3 Persistent Group (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
| function logSetElements(value1, value2, set) { | |
| console.log('set[' + value1 + '] = ' + value2); | |
| } | |
| class PGroup { | |
| constructor(pg = new Set()) { | |
| this.group = pg; | |
| } | |
| add(item) { | |
| let g = PGroup.from(this.group); | |
| g.group.add(item); | |
| return g; | |
| } | |
| delete(item) { | |
| let g = PGroup.from(this.group); | |
| g.group.delete(item); | |
| return g; | |
| } | |
| has(item) { | |
| return this.group.has(item); | |
| } | |
| static empty() { | |
| return new PGroup(); | |
| } | |
| static from(a) { | |
| let g = new PGroup(); | |
| for (let item of a) { | |
| g.group.add(item); | |
| } | |
| return g; | |
| } | |
| } | |
| let a = PGroup.empty().add("a"); | |
| let ab = a.add("b"); | |
| let b = ab.delete("a"); | |
| console.log(b.has("b")); | |
| // → true | |
| console.log(a.has("b")); | |
| // → false | |
| console.log(b.has("a")); | |
| // → false | |
| a.group.forEach(logSetElements); | |
| ab.group.forEach(logSetElements); | |
| b.group.forEach(logSetElements); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hints
The most convenient way to represent the set of member values remains is still an array, since those are easy to copy.
When a value is added to the group, you can create a new group with a copy of the original array that has the value added (for example using
concat). When a value is deleted, you filter it from the array.The class’ constructor can take such an array as argument, and store it as the instance’s (only) property. This array is never updated.
To add a property (
empty) to a constructor that is not a method, you have to add it to the constructor after the class definition, as a regular property.You only need one
emptyinstance because all empty groups are the same and instances of the class don’t change. You can create many different groups from that single empty group without affecting it.