()
| 19 | * |
| 20 | */ |
| 21 | export function createValueReuser() { |
| 22 | const values: unknown[] = []; |
| 23 | |
| 24 | function getOrReuse<T>(targetValue: T): T { |
| 25 | if (isPrimitive(targetValue)) { |
| 26 | return targetValue; |
| 27 | } |
| 28 | |
| 29 | if (values.includes(targetValue)) { |
| 30 | return targetValue; |
| 31 | } |
| 32 | |
| 33 | for (const [index, existingValue] of values.entries()) { |
| 34 | if (isPlainObjectEqual(existingValue, targetValue)) { |
| 35 | /** |
| 36 | * Move existing value to start of array so it will be found faster next time |
| 37 | */ |
| 38 | if (index === 0) return existingValue as T; |
| 39 | |
| 40 | const currentFirstValue = values[0]; |
| 41 | values[0] = existingValue; |
| 42 | values[index] = currentFirstValue; |
| 43 | return existingValue as T; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | values.unshift(targetValue); |
| 48 | |
| 49 | return targetValue; |
| 50 | } |
| 51 | |
| 52 | return getOrReuse; |
| 53 | } |
| 54 | |
| 55 | export type EqualValueReuser = ReturnType<typeof createValueReuser>; |
no outgoing calls
no test coverage detected