Convert JavaScript function to curried function.
Transform the function into functional programming
friendly function, like those in lodash
and date-fns
,
which support currying
and functional-style function composing.
If arity
is 0, toCurried
calls a function immediately and returns its result.
Function | *
: the resulted curried function (or the constant ifarity
is 0)
RangeError
:arity
must be non-negative number
Param | Type | Description |
---|---|---|
fn |
Function |
the function to convert |
arity |
Number |
the number of arguments of the resulted curried function |
[argsFn] |
Function |
callback that transforms the list of arguments |
import toCurried from 'to-curried'
function map (mapFn, xs) {
return xs.map(mapFn)
}
const curriedMap = toCurried(map, 2)
const multiplyEachBy2 = curriedMap(x => x * 2)
console.log(multiplyEachBy2([1, 2, 3, 4]))
//=> [2, 4, 6, 8]
// Change an order of arguments in curried function with optional callback:
import toCurried from 'to-curried'
function reduce (xs, reduceFn, initialValue) {
return xs.reduce(reduceFn, initialValue)
}
const curriedReduce = toCurried(reduce, 3, args => args.reverse())
const sum = curriedReduce(0, (a, b) => a + b)
console.log(sum([1, 2, 3, 4]))
// => 10