Skip to content

Instantly share code, notes, and snippets.

@AmesianX
Forked from corycook/enumerable.js
Created March 19, 2019 20:40
Show Gist options
  • Save AmesianX/cd2742aa703a5d804c75d38a28689d5c to your computer and use it in GitHub Desktop.
Save AmesianX/cd2742aa703a5d804c75d38a28689d5c 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