-
Notifications
You must be signed in to change notification settings - Fork 7
/
path.ts
34 lines (28 loc) · 1.26 KB
/
path.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
// Copyright (c) 2020 Jozty. All rights reserved. MIT license.
import type { ObjRec, PH } from './utils/types.ts';
import { Path, paths } from './paths.ts';
import curryN from './utils/curry_n.ts';
// @types
type PathF_2 = <T, R>(obj: ObjRec<T> | null) => R;
type PathF_1<T, R> = (ps: Path) => R;
type PathF =
& ((ps: Path) => PathF_2)
& (<T, R>(ps: PH, obj: ObjRec<T> | null) => PathF_1<T, R>)
& (<T, R>(ps: Path, obj: ObjRec<T> | null) => R);
function _path<R, T = unknown>(ps: Path, obj: ObjRec<T> | null): R {
return paths<T, R>([ps], obj)[0];
}
/**
* Retrieve the value at a given path.
* The path may be any array of keys or
* string of keys separated by `/` or `.` .
*
* Fae.path(['a', 'b'], {a: {b: 2}}); // 2
* Fae.path(['a', 'b'], {c: {b: 2}}); // undefined
* Fae.path('a/b/0', {a: {b: [1, 2, 3]}}); // 1
* Fae.path('a.b.0', {a: {b: [1, 2, 3]}}); // 1
* Fae.path('', {a: [1, 2, {ab: 5, de: [12, 23, 25]}, "234"], 4: "sdf"}); // {a: [1, 2, {ab: 5, de: [12, 23, 25]}, "234"], 4: "sdf"}
* Fae.path([], {a: [1, 2, {ab: 5, de: [12, 23, 25]}, "234"], 4: "sdf"}); // {a: [1, 2, {ab: 5, de: [12, 23, 25]}, "234"], 4: "sdf"}
* Fae.path(['a', ''], {a: {b: 2}}); // undefined
*/
export const path = curryN(2, _path) as PathF;