1 | import { isPlainObject as _iPO } from '../core/rtkImports'
|
2 |
|
3 |
|
4 | const isPlainObject: (_: any) => boolean = _iPO
|
5 |
|
6 | export function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T
|
7 | export function copyWithStructuralSharing(oldObj: any, newObj: any): any {
|
8 | if (
|
9 | oldObj === newObj ||
|
10 | !(
|
11 | (isPlainObject(oldObj) && isPlainObject(newObj)) ||
|
12 | (Array.isArray(oldObj) && Array.isArray(newObj))
|
13 | )
|
14 | ) {
|
15 | return newObj
|
16 | }
|
17 | const newKeys = Object.keys(newObj)
|
18 | const oldKeys = Object.keys(oldObj)
|
19 |
|
20 | let isSameObject = newKeys.length === oldKeys.length
|
21 | const mergeObj: any = Array.isArray(newObj) ? [] : {}
|
22 | for (const key of newKeys) {
|
23 | mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key])
|
24 | if (isSameObject) isSameObject = oldObj[key] === mergeObj[key]
|
25 | }
|
26 | return isSameObject ? oldObj : mergeObj
|
27 | }
|