Skip to content

Instantly share code, notes, and snippets.

@artalar
Created March 5, 2019 13:10
Show Gist options
  • Select an option

  • Save artalar/8cf38785cc152d6d3c8b889b07c36929 to your computer and use it in GitHub Desktop.

Select an option

Save artalar/8cf38785cc152d6d3c8b889b07c36929 to your computer and use it in GitHub Desktop.
class ArrayLazy extends Array {
_lazyQueue = [];
map(callback) {
this._lazyQueue.push({ type: "map", callback });
return this;
}
filter(callback) {
this._lazyQueue.push({ type: "filter", callback });
return this;
}
collect() {
const result = new ArrayLazy();
collect: for (let i = 0; i < this.length; i++) {
let value = this[i];
for (let j = 0; j < this._lazyQueue.length; j++) {
const { type, callback } = this._lazyQueue[j];
if (type === "filter") {
if (!callback(value)) continue collect;
} else {
// map
value = callback(value);
}
}
result.push(value);
}
this._lazyQueue = [];
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment