Created
March 6, 2016 20:21
-
-
Save cleac/c919766ea6482fb301d2 to your computer and use it in GitHub Desktop.
The python's generator implementation for javascript. Just for fun
This file contains hidden or 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
'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