Last active
July 13, 2021 11:51
-
-
Save Munawwar/83f70078ff7c740ee91a4d2c7fe23f0a to your computer and use it in GitHub Desktop.
Lodash chaining without importing the entire library
This file contains 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
function chain(value) { | |
return { | |
/** | |
* @param {function|string} func function or function name (in chained value) | |
* @param {...any} args | |
*/ | |
fn(func, ...args) { | |
if (typeof func === 'string') { | |
return chain(value[func](...args)); | |
} | |
return chain(func(value, ...args)); | |
}, | |
value, | |
}; | |
} | |
// -- usage -- | |
const { sortBy, keyBy, mapValues } = require('lodash'); | |
const data = [ | |
{ key: 'b', val: 2}, | |
{ key: 'a', val: 1}, | |
]; | |
console.log( | |
chain(data) | |
.fn(sortBy, 'key') | |
.fn(keyBy, 'key') | |
.fn(mapValues, ({ val }) => val) | |
.value, | |
); | |
// can also invoke built-in functions (like array.map) using string function names | |
console.log( | |
chain(data) | |
.fn('map', ({ key }) => [key, key]) | |
.fn(Object.fromEntries) | |
.value | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment