-
Notifications
You must be signed in to change notification settings - Fork 7
/
pathOr.ts
51 lines (41 loc) · 1.66 KB
/
pathOr.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Copyright (c) 2020 Jozty. All rights reserved. MIT license.
import type { ObjRec, PH } from './utils/types.ts';
import curryN from './utils/curry_n.ts';
import { defaultTo } from './defaultTo.ts';
import { path } from './path.ts';
import type { Path } from './paths.ts';
// @types
type PathOr_1 = <D, P>(d: D) => D | P;
type PathOr_2<D> = <P>(p: Path) => D | P;
type PathOr_3<D> = <T, P>(obj: ObjRec<T> | null) => D | P;
type PathOr_2_3<D> =
& ((p: Path) => PathOr_3<D>)
& (<T>(p: PH, obj: ObjRec<T> | null) => PathOr_2<D>)
& (<T, P>(p: Path, obj: ObjRec<T> | null) => D | P);
type PathOr_1_3 =
& (<D>(d: D) => PathOr_3<D>)
& (<T>(d: PH, obj: ObjRec<T> | null) => PathOr_1)
& (<T, D, P>(d: D, obj: ObjRec<T> | null) => D | P);
type PathOr_1_2<T> =
& (<D>(d: D) => PathOr_2<D>)
& ((d: PH, p: Path) => PathOr_1)
& (<D, P>(d: D, p: Path) => D | P);
type PathOr =
& (<D>(d: D) => PathOr_2_3<D>)
& ((d: PH, p: Path) => PathOr_1_3)
& (<T>(d: PH, p: PH, obj: ObjRec<T> | null) => PathOr_1_2<T>)
& (<D>(d: D, p: Path) => PathOr_3<D>)
& (<T, D>(d: D, p: PH, obj: ObjRec<T> | null) => PathOr_2<D>)
& (<T>(d: PH, p: Path, obj: ObjRec<T> | null) => PathOr_1)
& (<T, D, P>(d: D, p: Path, obj: ObjRec<T> | null) => D | P);
function _pathOr<T, D, P>(d: D, p: Path, obj: ObjRec<T> | null) {
return defaultTo(d, path<T, P>(p, obj));
}
/**
* If the given, non-null object has a value at the given path, returns the
* value at that path. Otherwise returns the provided default value.
*
* Fae.pathOr('N/A', ['a', 'b'], {a: {b: 2}}); //=> 2
* Fae.pathOr('N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A"
*/
export const pathOr = curryN(3, _pathOr) as PathOr;