-
-
Notifications
You must be signed in to change notification settings - Fork 426
Expand file tree
/
Copy pathutils.ts
More file actions
105 lines (87 loc) · 2.77 KB
/
utils.ts
File metadata and controls
105 lines (87 loc) · 2.77 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
export type NoInfer<A extends any> = [A][A extends any ? 0 : never]
export type PartialKeys<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>
/**
* checks whether the dependencies array has changed by comparing it with the previous one.
*
* @param newDeps new array of dependencies
* @param deps previous array of dependencies
* @returns `true` if the length of the arrays differ or if at least one dependency has changed; otherwise, `false`
*/
const isDepsChanged = <TDeps extends ReadonlyArray<any>>(
newDeps: Array<TDeps>,
deps: TDeps,
): boolean =>
newDeps.length !== deps.length ||
newDeps.some((dep, index: number) => deps[index] !== dep)
export function memo<TDeps extends ReadonlyArray<any>, TResult>(
getDeps: () => [...TDeps],
fn: (...args: NoInfer<[...TDeps]>) => TResult,
opts: {
key: false | string
debug?: () => boolean
onChange?: (result: TResult) => void
initialDeps?: TDeps
},
) {
let deps = opts.initialDeps ?? []
let result: TResult | undefined
function memoizedFunction(): TResult {
const enabledDebug = Boolean(opts.key && opts.debug?.())
let resultTime: number
let depTime: number
if (enabledDebug) {
depTime = Date.now()
}
const newDeps = getDeps()
if (!isDepsChanged(newDeps, deps)) {
return result!
}
deps = newDeps
if (enabledDebug) {
resultTime = Date.now()
}
result = fn(...newDeps)
if (enabledDebug) {
const depEndTime = Math.round((Date.now() - depTime!) * 100) / 100
const resultEndTime = Math.round((Date.now() - resultTime!) * 100) / 100
const resultFpsPercentage = resultEndTime / 16
console.info(
`%c⏱ ${String(resultEndTime).padStart(5, ' ')}/${String(depEndTime).padStart(5, ' ')} ms`,
`
font-size: .6rem;
font-weight: bold;
color: hsl(${Math.max(
0,
Math.min(120 - 120 * resultFpsPercentage, 120),
)}deg 100% 31%);`,
opts?.key,
)
}
opts?.onChange?.(result)
return result
}
// Attach updateDeps to the function itself
memoizedFunction.updateDeps = (newDeps: [...TDeps]) => {
deps = newDeps
}
return memoizedFunction
}
export function notUndefined<T>(value: T | undefined, msg?: string): T {
if (value === undefined) {
throw new Error(`Unexpected undefined${msg ? `: ${msg}` : ''}`)
} else {
return value
}
}
export const approxEqual = (a: number, b: number) => Math.abs(a - b) < 1
export const debounce = (
targetWindow: Window & typeof globalThis,
fn: Function,
ms: number,
) => {
let timeoutId: number
return function (this: any, ...args: Array<any>) {
targetWindow.clearTimeout(timeoutId)
timeoutId = targetWindow.setTimeout(() => fn.apply(this, args), ms)
}
}