Skip to content

Instantly share code, notes, and snippets.

@ZhihaoLau
Last active October 5, 2016 16:14
Show Gist options
  • Save ZhihaoLau/1f1391411bc2661d690b044d0a58b79f to your computer and use it in GitHub Desktop.
Save ZhihaoLau/1f1391411bc2661d690b044d0a58b79f to your computer and use it in GitHub Desktop.
createIterator - the es5 way
function createIterator(items) {
var i = 0;
return {
next: function() {
// NZakas' way is really straight forward what 'done' and 'value' is.
var done = (i >= items.length);
var value = done ? undefined : items[i++];
return {
done: done,
value: value
};
}
}
}
var it = createIterator([1, 2, 3]);
console.log(it.next()) // Object {done: false, value: 1}
console.log(it.next()) // Object {done: false, value: 2}
console.log(it.next()) // Object {done: false, value: 3}
console.log(it.next()) // Object {done: true, value: undefined}
console.log(it.next()) // Object {done: true, value: undefined}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment