Skip to content

Instantly share code, notes, and snippets.

@OzieWest
Created July 17, 2017 11:51
Show Gist options
  • Select an option

  • Save OzieWest/8a9c82f59e5f165d2d788118b617a50d to your computer and use it in GitHub Desktop.

Select an option

Save OzieWest/8a9c82f59e5f165d2d788118b617a50d to your computer and use it in GitHub Desktop.
Simple impl of lodash.chain
function map(arr, fn) {
console.log('invoked map');
if (arr) {
return arr.map(fn);
}
return [];
}
function filter(arr, fn) {
console.log('invoked filter');
if (arr) {
return arr.filter(fn);
}
return [];
}
function reduce(arr, fn, def) {
console.log('invoked reduce');
if (arr) {
return arr.reduce(fn, def);
}
return def;
}
function chain(arr) {
const ctx = {};
const stack = [() => arr];
const pushOrigin = stack.push.bind(stack);
stack.push = (elm) => {
console.log('push', stack);
pushOrigin(elm);
return ctx;
};
ctx.value = () => stack.pop()();
ctx.map = (fn) => stack.push(
() => map(ctx.value(), fn)
);
ctx.filter = (fn) => stack.push(
() => filter(ctx.value(), fn)
);
ctx.reduce = (fn, def) => stack.push(
() => reduce(ctx.value(), fn, def)
);
return ctx;
}
console.log(
chain([1, 2, 3])
.map(n => n * 4)
.filter(n => n > 5)
.reduce((mem, item) => item + mem, 0)
.value()
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment