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