refactor to account for variadic functions
altough certainly more verbose, this version accounts for variadic functions such as Math.min that can't represent it's arity with the length property properly. for such cases you can pass the optional argument arity (as in the edited example). what do you think?
This commit is contained in:
committed by
GitHub
parent
868f043ea0
commit
576b96a0f8
@ -5,8 +5,15 @@ If the number of provided arguments (`args`) is sufficient, call the passed func
|
||||
Otherwise return a curried function `f` that expects the rest of the arguments.
|
||||
|
||||
```js
|
||||
const curry = f =>
|
||||
(...args) =>
|
||||
args.length >= f.length ? f(...args) : (...otherArgs) => curry(f)(...args, ...otherArgs);
|
||||
const curry = (f, arity = f.length, next) =>
|
||||
(next = prevArgs =>
|
||||
nextArg => {
|
||||
const args = [ ...prevArgs, nextArg ]
|
||||
return args.length >= arity
|
||||
? f(...args)
|
||||
: next(args);
|
||||
}
|
||||
)([]);
|
||||
// curry(Math.pow)(2)(10) -> 1024
|
||||
// curry(Math.min, 3)(10)(50)(2) -> 2
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user