|
| 1 | +import { replaceEqualDeep } from "@tanstack/react-query"; |
| 2 | + |
| 3 | +/** Forked from https://github.com/epoberezkin/fast-deep-equal */ |
| 4 | +// biome-ignore lint/suspicious/noExplicitAny: This function by nature takes any object |
| 5 | +export function deepEqual(a: any, b: any) { |
| 6 | + if (a === b) return true; |
| 7 | + |
| 8 | + if (a && b && typeof a === "object" && typeof b === "object") { |
| 9 | + if (a.constructor !== b.constructor) return false; |
| 10 | + |
| 11 | + let length: number; |
| 12 | + let i: number; |
| 13 | + |
| 14 | + if (Array.isArray(a) && Array.isArray(b)) { |
| 15 | + length = a.length; |
| 16 | + if (length !== b.length) return false; |
| 17 | + for (i = length; i-- !== 0; ) if (!deepEqual(a[i], b[i])) return false; |
| 18 | + return true; |
| 19 | + } |
| 20 | + |
| 21 | + if (a.valueOf !== Object.prototype.valueOf) |
| 22 | + return a.valueOf() === b.valueOf(); |
| 23 | + if (a.toString !== Object.prototype.toString) |
| 24 | + return a.toString() === b.toString(); |
| 25 | + |
| 26 | + const keys = Object.keys(a); |
| 27 | + length = keys.length; |
| 28 | + if (length !== Object.keys(b).length) return false; |
| 29 | + |
| 30 | + for (i = length; i-- !== 0; ) |
| 31 | + // biome-ignore lint/style/noNonNullAssertion: We know its there |
| 32 | + if (!Object.prototype.hasOwnProperty.call(b, keys[i]!)) return false; |
| 33 | + |
| 34 | + for (i = length; i-- !== 0; ) { |
| 35 | + const key = keys[i]; |
| 36 | + |
| 37 | + if (key && !deepEqual(a[key], b[key])) return false; |
| 38 | + } |
| 39 | + |
| 40 | + return true; |
| 41 | + } |
| 42 | + |
| 43 | + // true if both NaN, false otherwise |
| 44 | + // biome-ignore lint/suspicious/noSelfCompare: <explanation> |
| 45 | + return a !== a && b !== b; |
| 46 | +} |
| 47 | + |
| 48 | +export function structuralSharing<T>(oldData: T | undefined, newData: T) { |
| 49 | + if (deepEqual(oldData, newData)) { |
| 50 | + return oldData as T; |
| 51 | + } |
| 52 | + return replaceEqualDeep(oldData, newData) as T; |
| 53 | +} |
0 commit comments