Advertisement
Guest User

Untitled

a guest
Feb 17th, 2018
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Here's a link to the 3rd edition draft, chapter 6 (exercises are on the very bottom):
  3.  
  4. http://eloquentjavascript.net/3rd_edition/06_object.html
  5.  
  6. Here's also the exercise description:
  7.  
  8. Iterable groups
  9. Make the Group class from the previous exercise iterable. Refer back to the section about the iterator interface earlier in the chapter if you aren’t clear on the exact form of the interface anymore. If you used an array to represent the group’s members, don’t just return the iterator created by calling the Symbol.iterator method on the array. That would work, but defeats the purpose of this exercise. It is okay if your iterator behaves strangely when the group is modified during iteration.
  10.  
  11. My code of "Group" is solid and has been tested on the page. The GroupIterator class was added, as well as the prototype assignment.
  12.  
  13. My problem is:
  14.  
  15. I have no idea how to call the object that is being iterated, neither any idea on how to call each iteration value. The example used to describe this idea was drawing a matrix, where adding numbers to x and y sufficed. What am I missing here?
  16.  
  17. Cheers
  18.  
  19. */
  20.  
  21. class Group {
  22.     constructor(){
  23.         this.array = []
  24.     };
  25.  
  26.     add(value) {
  27.         if (!this.array.includes(value)) {
  28.             this.array.push(value);
  29.         }
  30.     }
  31.     delete(value) {
  32.         if (this.array.includes(value)) {
  33.             let valueIndex = this.array.indexOf(value);
  34.             delete this.array[valueIndex];
  35.         }
  36.     }
  37.     has(value) {
  38.         if (this.array.includes(value)) return true;
  39.         else return false;
  40.     }
  41.  
  42.     static from(iterObj) {
  43.         let x = new Group();
  44.         for (this.iter of iterObj) {
  45.             x.add(this.iter);
  46.         }
  47.         return x;
  48.     }
  49. }
  50.  
  51. class GroupIterator {
  52.     constructor(group) {
  53.         this.group = group;
  54.         this.item = 0;
  55.     }
  56.  
  57.     next() {
  58.         if (this.item == this.group.array.length) {
  59.             return {done: true};
  60.         }
  61.         this.item++;
  62.         return {val: this.item, done: false};
  63.     }
  64. }
  65.  
  66. Group.prototype[Symbol.iterator] = function() {
  67.     return new GroupIterator(this);
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement