| 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 | |
| 8 | import {reuseEqualObjects} from '../deepEqualExt'; |
| 9 | |
| 10 | describe('reuseEqualObjects', () => { |
| 11 | it('makes === test work like deep equal', () => { |
| 12 | const oldArray = [ |
| 13 | {id: 'a', value: 1}, |
| 14 | {id: 'b', value: 2}, |
| 15 | {id: 'c', value: 3}, |
| 16 | {id: 'z', value: 5}, |
| 17 | ]; |
| 18 | const newArray = [ |
| 19 | {id: 'b', value: 2}, |
| 20 | {id: 'a', value: 1}, |
| 21 | {id: 'c', value: 4}, |
| 22 | {id: 'x', value: 3}, |
| 23 | ]; |
| 24 | const reusedArray = reuseEqualObjects(oldArray, newArray, v => v.id); |
| 25 | |
| 26 | expect(oldArray[0]).toBe(reusedArray[1]); // 'a' - reused |
| 27 | expect(oldArray[1]).toBe(reusedArray[0]); // 'b' - reused |
| 28 | |
| 29 | const objToId = new Map<object, number>(); |
| 30 | const toId = (obj: object): number => { |
| 31 | const id = objToId.get(obj); |
| 32 | if (id === undefined) { |
| 33 | const newId = objToId.size; |
| 34 | objToId.set(obj, newId); |
| 35 | return newId; |
| 36 | } |
| 37 | return id; |
| 38 | }; |
| 39 | |
| 40 | const oldIds = oldArray.map(toId); |
| 41 | const newIds = newArray.map(toId); |
| 42 | const reusedIds = reusedArray.map(toId); |
| 43 | |
| 44 | expect(oldIds).toEqual([0, 1, 2, 3]); |
| 45 | expect(newIds).toEqual([4, 5, 6, 7]); |
| 46 | expect(reusedIds).toEqual([1, 0, 6, 7]); // 'a', 'b' are reused from oldArray; 'c', 'x' are from newArray. |
| 47 | }); |
| 48 | }); |
| 49 | |