1 | import { curryN, identical, partial, pathOr, unary, when } from 'ramda';
|
---|
2 |
|
---|
3 | /**
|
---|
4 | * If the given, non-null object has a value at the given path, returns the value at that path.
|
---|
5 | * Otherwise returns the result of invoking the provided function with the object.
|
---|
6 | *
|
---|
7 | * @func pathOrLazy
|
---|
8 | * @memberOf RA
|
---|
9 | * @since {@link https://char0n.github.io/ramda-adjunct/2.22.0|v2.22.0}
|
---|
10 | * @category Object
|
---|
11 | * @typedef Idx = String | Int
|
---|
12 | * @sig ({a} -> a) -> [Idx] -> {a} -> a
|
---|
13 | * @param {Function} defaultFn The function that will return the default value.
|
---|
14 | * @param {Array} path The path to use.
|
---|
15 | * @param {Object} obj The object to retrieve the nested property from.
|
---|
16 | * @return {*} The data at `path` of the supplied object or the default value.
|
---|
17 | * @example
|
---|
18 | *
|
---|
19 | * RA.pathOrLazy(() => 'N/A', ['a', 'b'], {a: {b: 2}}); //=> 2
|
---|
20 | * RA.pathOrLazy(() => 'N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A"
|
---|
21 | */
|
---|
22 | const pathOrLazy = curryN(3, (defaultFn, path, obj) =>
|
---|
23 | when(
|
---|
24 | identical(defaultFn),
|
---|
25 | partial(unary(defaultFn), [obj]),
|
---|
26 | pathOr(defaultFn, path, obj)
|
---|
27 | )
|
---|
28 | );
|
---|
29 |
|
---|
30 | export default pathOrLazy;
|
---|