1 | import { isNil, curryN, curry, apply } from 'ramda';
|
---|
2 |
|
---|
3 | import defaultWhen from './defaultWhen';
|
---|
4 | import mapIndexed from './mapIndexed';
|
---|
5 |
|
---|
6 | /**
|
---|
7 | * Returns a function which is called with the given arguments. If any of the given arguments are null or undefined,
|
---|
8 | * the corresponding default value for that argument is used instead.
|
---|
9 | *
|
---|
10 | * @func fnull
|
---|
11 | * @memberOf RA
|
---|
12 | * @category Function
|
---|
13 | * @sig (a ... -> b) -> [c] -> a ... | c -> b
|
---|
14 | * @param {Function} function to be executed
|
---|
15 | * @param {Array} defaults default arguments
|
---|
16 | * @return {Function} will apply provided arguments or default ones
|
---|
17 | * @example
|
---|
18 | *
|
---|
19 | * const addDefaults = RA.fnull((a, b) => a + b, [4, 5])
|
---|
20 | *
|
---|
21 | * addDefaults(1, 2); // => 3
|
---|
22 | * addDefaults(null, 2); // => 6
|
---|
23 | * addDefaults(2, null); // => 7
|
---|
24 | * addDefaults(undefined, undefined); // => 9
|
---|
25 | */
|
---|
26 |
|
---|
27 | const fnull = curry((fn, defaults) =>
|
---|
28 | curryN(fn.length, (...args) => {
|
---|
29 | const argsWithDefaults = mapIndexed(
|
---|
30 | (val, idx) => defaultWhen(isNil, defaults[idx], val),
|
---|
31 | args
|
---|
32 | );
|
---|
33 |
|
---|
34 | return apply(fn, argsWithDefaults);
|
---|
35 | })
|
---|
36 | );
|
---|
37 |
|
---|
38 | export default fnull;
|
---|