| b69ab31 | | | 1 | /** |
| b69ab31 | | | 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| b69ab31 | | | 3 | * |
| b69ab31 | | | 4 | * This source code is licensed under the MIT license found in the |
| b69ab31 | | | 5 | * LICENSE file in the root directory of this source tree. |
| b69ab31 | | | 6 | */ |
| b69ab31 | | | 7 | |
| b69ab31 | | | 8 | import {reuseEqualObjects} from '../deepEqualExt'; |
| b69ab31 | | | 9 | |
| b69ab31 | | | 10 | describe('reuseEqualObjects', () => { |
| b69ab31 | | | 11 | it('makes === test work like deep equal', () => { |
| b69ab31 | | | 12 | const oldArray = [ |
| b69ab31 | | | 13 | {id: 'a', value: 1}, |
| b69ab31 | | | 14 | {id: 'b', value: 2}, |
| b69ab31 | | | 15 | {id: 'c', value: 3}, |
| b69ab31 | | | 16 | {id: 'z', value: 5}, |
| b69ab31 | | | 17 | ]; |
| b69ab31 | | | 18 | const newArray = [ |
| b69ab31 | | | 19 | {id: 'b', value: 2}, |
| b69ab31 | | | 20 | {id: 'a', value: 1}, |
| b69ab31 | | | 21 | {id: 'c', value: 4}, |
| b69ab31 | | | 22 | {id: 'x', value: 3}, |
| b69ab31 | | | 23 | ]; |
| b69ab31 | | | 24 | const reusedArray = reuseEqualObjects(oldArray, newArray, v => v.id); |
| b69ab31 | | | 25 | |
| b69ab31 | | | 26 | expect(oldArray[0]).toBe(reusedArray[1]); // 'a' - reused |
| b69ab31 | | | 27 | expect(oldArray[1]).toBe(reusedArray[0]); // 'b' - reused |
| b69ab31 | | | 28 | |
| b69ab31 | | | 29 | const objToId = new Map<object, number>(); |
| b69ab31 | | | 30 | const toId = (obj: object): number => { |
| b69ab31 | | | 31 | const id = objToId.get(obj); |
| b69ab31 | | | 32 | if (id === undefined) { |
| b69ab31 | | | 33 | const newId = objToId.size; |
| b69ab31 | | | 34 | objToId.set(obj, newId); |
| b69ab31 | | | 35 | return newId; |
| b69ab31 | | | 36 | } |
| b69ab31 | | | 37 | return id; |
| b69ab31 | | | 38 | }; |
| b69ab31 | | | 39 | |
| b69ab31 | | | 40 | const oldIds = oldArray.map(toId); |
| b69ab31 | | | 41 | const newIds = newArray.map(toId); |
| b69ab31 | | | 42 | const reusedIds = reusedArray.map(toId); |
| b69ab31 | | | 43 | |
| b69ab31 | | | 44 | expect(oldIds).toEqual([0, 1, 2, 3]); |
| b69ab31 | | | 45 | expect(newIds).toEqual([4, 5, 6, 7]); |
| b69ab31 | | | 46 | expect(reusedIds).toEqual([1, 0, 6, 7]); // 'a', 'b' are reused from oldArray; 'c', 'x' are from newArray. |
| b69ab31 | | | 47 | }); |
| b69ab31 | | | 48 | }); |