Skip to content

Instantly share code, notes, and snippets.

@corycook
Created October 29, 2015 23:57
Show Gist options
  • Save corycook/81c9f4df79ae94d325a2 to your computer and use it in GitHub Desktop.
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.
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