Skip to content

Instantly share code, notes, and snippets.

@Munawwar
Last active July 3, 2020 17:28
Show Gist options
  • Save Munawwar/5e36d8799098322d33754c42966813bb to your computer and use it in GitHub Desktop.
Save Munawwar/5e36d8799098322d33754c42966813bb to your computer and use it in GitHub Desktop.
Lodash-like chaining using reduce for Absurdum. Why? Cuz we can..
// Law of Absurd Reduces: Everything that can be implemented with reduce() will eventually be implemented with reduce()
/**
* @param {Object} chainableFunctions object where each key is the name of a function and it's value is the function itself
*/
const createChainables = (chainableFunctions) => ({
chain(initialValue) {
const operations = [];
const evaluate = () => operations.reduce(
(value, [func, ...args]) => func(value, ...args),
initialValue,
);
const proxy = Object
.keys(chainableFunctions)
.reduce((acc, funcName) => ({
...acc,
[funcName]: (...args) => {
operations.push([chainableFunctions[funcName], ...args]);
return proxy;
},
}), { value: evaluate });
return proxy;
},
});
// -- usage --
const { map } = require('@vanillaes/absurdum').arrays;
const { fromEntries } = require('@vanillaes/absurdum').objects;
const _ = createChainables({
map,
fromEntries,
})
const data = [
{ key: 'a', val: 1},
{ key: 'b', val: 2},
];
console.log(
_
.chain(data)
.map(({ key, val }) => [key, val])
.fromEntries()
.value()
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment