Skip to content

Instantly share code, notes, and snippets.

@AGhost-7
Last active November 30, 2020 23:41
Show Gist options
  • Save AGhost-7/5d97bbaba5093901d9a86a32ee144902 to your computer and use it in GitHub Desktop.
Save AGhost-7/5d97bbaba5093901d9a86a32ee144902 to your computer and use it in GitHub Desktop.
Example of a lazy collection which only creates one new array even with multiple combinator calls
const assert = require('assert');
class BaseIter {
map(fn) {
return new MapIter(this, fn);
}
filter(fn) {
return new FilterIter(this, fn);
}
collect() {
const result = [];
let {done, value} = this._iter.next();
while (!done) {
result.push(value);
({done, value} = this._iter.next());
}
return result;
}
}
class MapIter extends BaseIter {
constructor(iter, fn) {
super();
this._iter = iter;
this._fn = fn;
}
next() {
const {done, value} = this._iter.next();
return {
done,
value: done ? value : this._fn(value)
};
}
}
class FilterIter extends BaseIter {
constructor(iter, fn) {
super();
this._iter = iter;
this._fn = fn;
}
next() {
let {done, value} = this._iter.next();
while (!done && !this._fn(value)) {
({done, value} = this._iter.next());
}
return {done, value};
}
}
class LazyIter extends BaseIter {
constructor(values) {
super();
assert(values[Symbol.iterator], 'Input must have a iterator');
this._iter = values[Symbol.iterator]();
}
next() {
return this._iter.next();
}
}
const result = new LazyIter([1, 2, 3, 4])
.map(value => {
console.log('map1 going through value %d', value);
return value * 3;
})
.filter(value => {
console.log('filter1 going through value %d', value);
return value % 6 === 0;
})
.map(value => {
console.log('map2 going through value %d', value);
return value * 10;
})
.collect();
console.log('result', result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment