(requireAllKeys = true)
| 2 | * Helper utility that updates the specified callback whenever any of the specified indices have changed. |
| 3 | */ |
| 4 | export function createCallbackMemoizer(requireAllKeys = true) { |
| 5 | let cachedIndices: Record<string, unknown> = {}; |
| 6 | |
| 7 | return <Indices extends object>({ |
| 8 | callback, |
| 9 | indices |
| 10 | }: { |
| 11 | callback: (indices: Indices) => void; |
| 12 | indices: Indices; |
| 13 | }) => { |
| 14 | const indicesMap = indices as Record<string, unknown>; |
| 15 | const keys = Object.keys(indices); |
| 16 | const allInitialized = |
| 17 | !requireAllKeys || |
| 18 | keys.every((key) => { |
| 19 | const value = indicesMap[key]; |
| 20 | return Array.isArray(value) ? value.length > 0 : (value as number) >= 0; |
| 21 | }); |
| 22 | const indexChanged = |
| 23 | keys.length !== Object.keys(cachedIndices).length || |
| 24 | keys.some((key) => { |
| 25 | const cachedValue = cachedIndices[key]; |
| 26 | const value = indicesMap[key]; |
| 27 | |
| 28 | return Array.isArray(value) |
| 29 | ? (cachedValue as unknown[]).join(",") !== value.join(",") |
| 30 | : cachedValue !== value; |
| 31 | }); |
| 32 | |
| 33 | cachedIndices = indicesMap; |
| 34 | |
| 35 | if (allInitialized && indexChanged) { |
| 36 | callback(indices); |
| 37 | } |
| 38 | }; |
| 39 | } |
no test coverage detected