1 | import { pipe, curry, find, defaultTo } from 'ramda';
|
---|
2 |
|
---|
3 | /**
|
---|
4 | * Returns the first element of the list which matches the predicate.
|
---|
5 | * Returns default value if no element matches or matched element is `null`, `undefined` or `NaN`.
|
---|
6 | * Dispatches to the find method of the second argument, if present.
|
---|
7 | * Acts as a transducer if a transformer is given in list position.
|
---|
8 | *
|
---|
9 | * @func findOr
|
---|
10 | * @memberOf RA
|
---|
11 | * @since {@link https://char0n.github.io/ramda-adjunct/2.32.0|v2.32.0}
|
---|
12 | * @category List
|
---|
13 | * @sig a -> (b -> Boolean) -> [b] -> b | a
|
---|
14 | * @param {*} defaultValue The default value
|
---|
15 | * @param {Function} fn The predicate function used to determine if the element is the desired one.
|
---|
16 | * @param {Array} list The array to consider.
|
---|
17 | * @return {*} The element found, or the default value.
|
---|
18 | * @see {@link http://ramdajs.com/docs/#defaultTo|R.defaultTo}, {@link http://ramdajs.com/docs/#find|R.find}
|
---|
19 | * @example
|
---|
20 | *
|
---|
21 | * RA.findOr(1, isUndefined, [1, 2, undefined]); // => 1
|
---|
22 | * RA.findOr(1, val => val === 2, [1, 2, undefined]); // => 2
|
---|
23 | * RA.findOr(1, val => val === 3, [1, 2, undefined]); // => 1
|
---|
24 | */
|
---|
25 |
|
---|
26 | const findOr = curry((defaultVal, fn, list) =>
|
---|
27 | pipe(find(fn), defaultTo(defaultVal))(list)
|
---|
28 | );
|
---|
29 |
|
---|
30 | export default findOr;
|
---|