addons/shared/deepEqualExt.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318import deepEqual from 'fast-deep-equal';
b69ab319
b69ab3110/** Try to reuse objects from `oldArray` for objects with the same key and deepEqual values. */
b69ab3111export function reuseEqualObjects<T>(
b69ab3112 oldArray: Array<T>,
b69ab3113 newArray: Array<T>,
b69ab3114 keyFunc: (value: T) => string,
b69ab3115 equalFunc: (a: T, b: T) => boolean = deepEqual,
b69ab3116): Array<T> {
b69ab3117 const oldMap = new Map<string, T>(oldArray.map(v => [keyFunc(v), v]));
b69ab3118 return newArray.map(value => {
b69ab3119 const oldValue = oldMap.get(keyFunc(value));
b69ab3120 return oldValue && equalFunc(oldValue, value) ? oldValue : value;
b69ab3121 });
b69ab3122}