Created
October 29, 2015 23:57
-
-
Save corycook/81c9f4df79ae94d325a2 to your computer and use it in GitHub Desktop.
Using Object.defineProperty to fake an Array-like object that can be iterated over with a for loop or Array.prototype.slice.
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 Enumerable(generator, length, start) { | |
this.generator = generator; | |
this.length = length || Infinity; | |
this.current = start || 0; | |
this.index = 0; | |
Object.defineProperty(this, this.index, { get: this.next, configurable: true }); | |
} | |
Enumerable.prototype.next = function() { | |
if (this.index < this.length) { | |
Object.defineProperty(this, this.index, { value: this.current }); | |
Object.defineProperty(this, this.index + 1, { get: this.next, configurable: true }); | |
this.index = this.index + 1; | |
this.current = this.generator(this.current); | |
} | |
return this.current; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment