I'm not sure of there is a proposal for this. Would it make sense to have a compose
helper function on Function
or its prototype
? I often come across situations where I have to nest function calls to pass data. I was thinking along the lines of map
ping of functions, like arrays.
Code like this
const objectInvert = (obj) => {
return Object.fromEntries(
Object.entries(obj).map(entry => entry.reverse())
);
}
can be converted to
const objectInvert = Function.compose(
Object.entries,
(entries) => entries.map(entry => entry.reverse()),
Object.fromEntries,
);
Here's a very rough polyfill for Function.compose
.
Function.compose = function(...args) {
return (input) => {
return args.reduce((acc, fn) => {
return fn(acc);
}, input);
}
}
Alternatively, on the prototype
Function.prototype.compose = function(fn) {
const currentFn = this;
return (...args) => {
return fn(currentFn(...args));
}
}
and we can do things like this --
function add(a, b) {
return a + b;
}
const square = el => el => el ** 2;
const sumSquare = add.compose(square);
Would compose
like this make sense? Or would this only work with explicit currying support?
Feedback welcome! Thanks!