Last active
September 3, 2015 05:18
-
-
Save RinatMullayanov/b0773f61e7899e023f00 to your computer and use it in GitHub Desktop.
ES 2015 iterator sample based on http://learn.javascript.ru/iterator
This file contains 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 () { | |
'use strict'; | |
let range = { | |
from: 1, | |
to: 5 | |
} | |
// make object range iterable | |
range[Symbol.iterator] = function() { | |
let current = this.from; | |
let last = this.to; | |
// method must return object with next() | |
return { | |
next() { | |
if (current <= last) { | |
return { | |
done: false, | |
value: current++ | |
}; | |
} else { | |
return { | |
done: true | |
}; | |
} | |
} | |
} | |
}; | |
for (let num of range) { | |
console.log(num); // 1, 2, 3, 4, 5 | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment