742 B23 lines
Blame
1/**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8import deepEqual from 'fast-deep-equal';
9
10/** Try to reuse objects from `oldArray` for objects with the same key and deepEqual values. */
11export function reuseEqualObjects<T>(
12 oldArray: Array<T>,
13 newArray: Array<T>,
14 keyFunc: (value: T) => string,
15 equalFunc: (a: T, b: T) => boolean = deepEqual,
16): Array<T> {
17 const oldMap = new Map<string, T>(oldArray.map(v => [keyFunc(v), v]));
18 return newArray.map(value => {
19 const oldValue = oldMap.get(keyFunc(value));
20 return oldValue && equalFunc(oldValue, value) ? oldValue : value;
21 });
22}
23