by goldenkey · 5y ago · 0 comments
const curry = fn => {
return (...args) => {
const curried = (...a) => {
args = [...args]
return args.push(...a) >= fn.length ? fn(...args) : curried
}
return curried()
}
}As for the inelegant claim, beauty is in the eye of the beholder. If performance is not a concern (as it won't be in most currying use-cases) I think the original version is much easier to read without years of js experience. It can be hard for newer or cross-discipline devs to understand mixed usage of rest params and spread operator since they look the same. In a scenario like this I think maintainability is a key ingredient of elegance.
const curry = fn => {
const curried = (...a) => a.length >= fn.length ? fn(...a) : curried.bind(undefined, ...a)
return curried
}
It uses bind which is an extremely powerful operator (a function that maps functions to functions) const sum3 = curry(( a, b, c ) => a + b + c )
const sum3_10 = sum3( 10 ) // ...
const sum3_10_20 = sum3_10( 20 ) // ...
sum3_10_20( 30 ) // 60
sum3_10_20( 5 ) // 60
One of the points of currying is to be able to fork the partial application of the function at any point. const curry = fn => {
const curried = (...a) => a.length >= fn.length ? fn(...a) : curried.bind(undefined, ...a)
return curried
}