Skip to content

Instantly share code, notes, and snippets.

@wesalvaro
Last active August 15, 2016 04:55
Show Gist options
  • Save wesalvaro/218dfcf5613b9bf55ad9e8329ea368fd to your computer and use it in GitHub Desktop.
Save wesalvaro/218dfcf5613b9bf55ad9e8329ea368fd to your computer and use it in GitHub Desktop.
Wraps an Array with generator functions.
const it = function(a) {
return new Aarray(a2g(a));
};
const a2g = function*(a) {
for (let v of a) {
yield v;
}
};
const Aarray = function(g) {
this.g = g;
};
Aarray.prototype.map = function(f) {
const og = this.g;
this.g = (function*() {
for (let v of og) {
yield f(v);
}
}());
return this;
};
Aarray.prototype.filter = function(f) {
const og = this.g;
this.g = (function*() {
for (let v of og) {
if (f(v)) yield v;
}
}());
return this;
};
Aarray.prototype[Symbol.iterator] = function*() {
yield* this.g;
};
Aarray.prototype.find = function(f) {
for (let v of this.g) {
if (f(v)) return v;
}
};
/*
// Example:
const a = new Array(1e9); // Huge array
a[0] = '4'
a[1] = '42';
it(a).map(e => parseInt(e)).filter(e => e % 4).find(e => e%2 == 0);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment