|
| 1 | +/** |
| 2 | + * Copyright 2025 Adobe |
| 3 | + * All Rights Reserved. |
| 4 | + */ |
| 5 | + |
| 6 | +/* eslint-disable max-nested-callbacks */ |
| 7 | +define([ |
| 8 | + 'Magento_Ui/js/lib/core/collection', |
| 9 | + 'Magento_Ui/js/lib/core/element/element' |
| 10 | +], function (uiCollection, uiElement) { |
| 11 | + 'use strict'; |
| 12 | + |
| 13 | + describe('Magento_Ui/js/lib/core/collection', function () { |
| 14 | + describe('"insertChild" method', function () { |
| 15 | + it('should not slow down due to large position value', function () { |
| 16 | + const items = [ |
| 17 | + {name: 'elem-1', position: 2}, |
| 18 | + {name: 'elem-2', position: 0}, |
| 19 | + {name: 'elem-3', position: 1}, |
| 20 | + {name: 'elem-4', position: 5}, |
| 21 | + {name: 'elem-5', position: 9}, |
| 22 | + {name: 'elem-6', position: 3}, |
| 23 | + {name: 'elem-7', position: 8}, |
| 24 | + {name: 'elem-8', position: 4}, |
| 25 | + {name: 'elem-9', position: 7} |
| 26 | + ]; |
| 27 | + |
| 28 | + let collection, |
| 29 | + maxExecutionTime = 0, |
| 30 | + startTime; |
| 31 | + |
| 32 | + // Measure the maximum time taken to insert items with small position values |
| 33 | + for (let i = 0; i < 10; i++) { |
| 34 | + let tmpCollection = new uiCollection(); |
| 35 | + |
| 36 | + startTime = performance.now(); |
| 37 | + items.forEach(function (item) { |
| 38 | + tmpCollection.insertChild(new uiElement({name: item.name}), item.position); |
| 39 | + }); |
| 40 | + maxExecutionTime = Math.max(maxExecutionTime, performance.now() - startTime); |
| 41 | + } |
| 42 | + |
| 43 | + // Measure the time taken to insert items with a large position value |
| 44 | + items[0].position = 9999999; |
| 45 | + collection = new uiCollection(); |
| 46 | + startTime = performance.now(); |
| 47 | + items.forEach(function (item) { |
| 48 | + collection.insertChild(new uiElement({name: item.name}), item.position); |
| 49 | + }); |
| 50 | + |
| 51 | + // Verify that the time taken is not significantly longer than the normal execution time |
| 52 | + // This used to be around 6000ms versus 5ms (1000x slower). |
| 53 | + // But now it takes approximately the same time as normal execution. |
| 54 | + // Setting a threshold of 5 times the normal execution time to account for fluctuations. |
| 55 | + expect(performance.now() - startTime).toBeLessThan(5 * maxExecutionTime); |
| 56 | + |
| 57 | + // Verify that the items are sorted correctly |
| 58 | + expect( |
| 59 | + collection.elems().map(function (elem) { |
| 60 | + return elem.name; |
| 61 | + }) |
| 62 | + ).toEqual( |
| 63 | + items.slice() |
| 64 | + .sort(function (a, b) { |
| 65 | + return a.position - b.position; |
| 66 | + }) |
| 67 | + .map(function (elem) { |
| 68 | + return elem.name; |
| 69 | + }) |
| 70 | + ); |
| 71 | + }, 1000); |
| 72 | + }); |
| 73 | + }); |
| 74 | +}); |
0 commit comments