generated from garronej/ts-ci
-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
getDependencyArrayRef.ts
49 lines (42 loc) · 1.24 KB
/
getDependencyArrayRef.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
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* useEffect(
* ()=> { ... },
* [ { "foo": "bar" } ]
* )
* => The callback will be invoked every render.
* because { "foo": "bar" } is a new instance every render.
*
* useEffect(
* ()=> { ... },
* [ getDependencyArrayRef({ "foo": "bar" }) ]
* );
* => The callback will only be invoked once.
*
* The optimization will be enabled only if obj is
* of the form Record<string, string | number | undefined | null>
* otherwise the object is returned (the function is the identity function).
*/
export function getDependencyArrayRef(obj: any): any {
if (!(obj instanceof Object) || typeof obj === "function") {
return obj;
}
const arr: string[] = [];
for (const key in obj) {
const value = obj[key];
const typeofValue = typeof value;
if (
!(
typeofValue === "string" ||
(typeofValue === "number" && !isNaN(value)) ||
typeofValue === "boolean" ||
value === undefined ||
value === null
)
) {
return obj;
}
arr.push(`${key}:${typeofValue}_${value}`);
}
return "xSqLiJdLMd9s" + arr.join("|");
}