Skip to content

Instantly share code, notes, and snippets.

@Munawwar
Last active July 13, 2021 11:51
Show Gist options
  • Save Munawwar/83f70078ff7c740ee91a4d2c7fe23f0a to your computer and use it in GitHub Desktop.
Save Munawwar/83f70078ff7c740ee91a4d2c7fe23f0a to your computer and use it in GitHub Desktop.
Lodash chaining without importing the entire library
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