Last active
July 3, 2020 17:28
-
-
Save Munawwar/5e36d8799098322d33754c42966813bb to your computer and use it in GitHub Desktop.
Lodash-like chaining using reduce for Absurdum. Why? Cuz we can..
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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