to-curried
v1.0.0
Published
Convert JavaScript function to curried function
Readme
to-curried
Convert JavaScript function to curried function.
toCurried(fn, arity, [argsFn]) ⇒ 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.
Returns
Function | *: the resulted curried function (or the constant ifarityis 0)
Throws
RangeError:aritymust be non-negative number
Arguments
| 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 |
Example
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]Example
// 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