Skip to content

Instantly share code, notes, and snippets.

@cleac
Created March 6, 2016 20:21
Show Gist options
  • Save cleac/c919766ea6482fb301d2 to your computer and use it in GitHub Desktop.
Save cleac/c919766ea6482fb301d2 to your computer and use it in GitHub Desktop.
The python's generator implementation for javascript. Just for fun
'use strict';
function IntGenerator(start, end, step) {
this.start = start || 0;
this.current = start || 0;
this.end = end || this.current;
this.step = step || ((this.current > this.end) ? -1 : 1);
}
IntGenerator.prototype[Symbol.iterator] = function () {
return {
next: () => {
this.current += this.step
return {
done: this.start <= this.end ?
this.current > this.end :
this.current < this.end,
value: this.current,
};
},
};
}
var generator = new IntGenerator(1, 5);
for(var i of generator) {
console.log(i);
}
console.log("Running another one")
generator = new IntGenerator(1,10000)
for(var i of generator) {
console.log(i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment