Advertisement
Guest User

Untitled

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