Advertisement
juliarnasution

iterable javascript

Dec 3rd, 2019
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let range = {
  2.     from: 1,
  3.     to: 5
  4. };
  5. // 1. call to for..of initially calls this
  6. range[Symbol.iterator] = function () {
  7.     // ...it returns the iterator object:
  8.     // 2. Onward, for..of works only with this iterator, asking it for next values
  9.     return {
  10.         current: this.from,
  11.         last: this.to,
  12.  
  13.         // 3. next() is called on each iteration by the for..of loop
  14.         next() {
  15.             // 4. it should return the value as an object {done:.., value :...}
  16.             if (this.current <= this.last) {
  17.                 return { done: false, value: this.current++ };
  18.             } else {
  19.                 return { done: true };
  20.             }
  21.         }
  22.     };
  23. };
  24. console.log(range); //Object { from: 1, to: 5, Symbol(Symbol.iterator): Symbol.iterator() }
  25. console.log(range[Symbol.iterator]()); //Object { current: 1, last: 5, next: next() }
  26. console.log(range[Symbol.iterator]().next()); //Object { done: false, value: 1 }
  27. // now it works!
  28. for (let num of range) {
  29.     console.log(num); // 1, then 2, 3, 4, 5
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement