Skip to content

Instantly share code, notes, and snippets.

@Beraliv
Last active November 20, 2017 19:46
Show Gist options
  • Save Beraliv/bd412161db4b3e4ae1f27b8faba77535 to your computer and use it in GitHub Desktop.
Save Beraliv/bd412161db4b3e4ae1f27b8faba77535 to your computer and use it in GitHub Desktop.
Lazy Array operations: map, filter, reduce. Not completed.
let LazyArray = (() => {
let _arr = [];
let _ops = [];
const isEmpty = v => v === null || v === undefined;
const combine = (v, ...fns) => {
let result = v;
for (let { type, fn } of fns) {
if (isEmpty(result) || isEmpty(fn)) {
return undefined;
}
if (type === 'filter' && !fn(result)) {
return undefined;
}
if (type === 'map') {
result = fn(result);
}
}
return result;
};
return {
of(arr) {
_arr = arr;
_ops = [];
return this;
},
map(fn) {
_ops.push({ type: 'map', fn });
return this;
},
filter(fn) {
_ops.push({ type: 'filter', fn });
return this;
},
// TODO: yet not working, returned NaN
reduce(fn, base) {
const op = v => combine(v, ..._ops);
const cb = (acc, value) => {
if (!isEmpty(value)) {
return fn(acc, op(value));
}
return acc;
};
return base ? _arr.reduce(cb, base) : _arr.reduce(cb);
},
get() {
const op = v => combine(v, ..._ops);
return _arr.reduce((arr, value) => {
let modified = op(value);
if (!isEmpty(modified)) {
arr.push(modified);
}
return arr;
}, []);
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment