addons/shared/__tests__/deepEqualExt.test.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 {reuseEqualObjects} from '../deepEqualExt';
b69ab319
b69ab3110describe('reuseEqualObjects', () => {
b69ab3111 it('makes === test work like deep equal', () => {
b69ab3112 const oldArray = [
b69ab3113 {id: 'a', value: 1},
b69ab3114 {id: 'b', value: 2},
b69ab3115 {id: 'c', value: 3},
b69ab3116 {id: 'z', value: 5},
b69ab3117 ];
b69ab3118 const newArray = [
b69ab3119 {id: 'b', value: 2},
b69ab3120 {id: 'a', value: 1},
b69ab3121 {id: 'c', value: 4},
b69ab3122 {id: 'x', value: 3},
b69ab3123 ];
b69ab3124 const reusedArray = reuseEqualObjects(oldArray, newArray, v => v.id);
b69ab3125
b69ab3126 expect(oldArray[0]).toBe(reusedArray[1]); // 'a' - reused
b69ab3127 expect(oldArray[1]).toBe(reusedArray[0]); // 'b' - reused
b69ab3128
b69ab3129 const objToId = new Map<object, number>();
b69ab3130 const toId = (obj: object): number => {
b69ab3131 const id = objToId.get(obj);
b69ab3132 if (id === undefined) {
b69ab3133 const newId = objToId.size;
b69ab3134 objToId.set(obj, newId);
b69ab3135 return newId;
b69ab3136 }
b69ab3137 return id;
b69ab3138 };
b69ab3139
b69ab3140 const oldIds = oldArray.map(toId);
b69ab3141 const newIds = newArray.map(toId);
b69ab3142 const reusedIds = reusedArray.map(toId);
b69ab3143
b69ab3144 expect(oldIds).toEqual([0, 1, 2, 3]);
b69ab3145 expect(newIds).toEqual([4, 5, 6, 7]);
b69ab3146 expect(reusedIds).toEqual([1, 0, 6, 7]); // 'a', 'b' are reused from oldArray; 'c', 'x' are from newArray.
b69ab3147 });
b69ab3148});