-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathget-value.ts
68 lines (61 loc) · 1.73 KB
/
get-value.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Please refer to the terms of the license agreement in the root of the project
*
* (c) 2024 Feedzai
*/
import { at, isObject, isUndefined } from "..";
type Payload = {
defaultValue?: unknown;
required?: boolean;
};
/**
* Gets the value corresponding to the path of an object.
*
* If the object is required to have that path and the path does not exist, there are 2 possible outcomes:
* if a default value is provided, a warning is emitted indicating that value. If not, an error is emitted.
*
* If the object is not required to have that path, the default value (provided or undefined) is returned,
* without any warning.
*
* @example
*
* ```js
* import { getValue } from '@feedzai/js-utilities';
*
* const OBJ = {
* a: {
* b: {
* c: 123,
* },
* },
* };
*
* const RESULT = getValue(OBJ, "a.b.d", { defaultValue: "a-default-value", required: true });
* // => "a-default-value"
* ```
*/
export function getValue<T, R = unknown>(
object: T,
path: string,
payload?: Payload | unknown
): R | undefined {
const TYPED_PAYLOAD = isObject(payload) ? (payload as Payload) : undefined;
const DEFAULT_VAL = TYPED_PAYLOAD?.defaultValue;
const RESULT = at(object, path)[0];
const IS_REQUIRED = TYPED_PAYLOAD?.required ?? false;
if (!isUndefined(RESULT)) {
return RESULT as R;
}
if (!IS_REQUIRED) {
return DEFAULT_VAL as R;
}
if (!isUndefined(DEFAULT_VAL)) {
console.warn(
`[@feedzai/js-utilities] The path ${path} does not exist on the object. Using ${DEFAULT_VAL} instead.`
);
return DEFAULT_VAL as R;
}
console.error(`[@feedzai/js-utilities] The path ${path} does not exist on the object.`);
return undefined;
}