diff --git a/cocos/core/algorithm/move.ts b/cocos/core/algorithm/move.ts new file mode 100644 index 0000000000..cd541ca043 --- /dev/null +++ b/cocos/core/algorithm/move.ts @@ -0,0 +1,27 @@ +import { assertsArrayIndex } from '../data/utils/asserts'; + +/** + * Moves an array element to new location. + * @param array The array. + * @param index Index to the array element to move. + * @param newIndex New array index it should have. + */ +export function move (array: T[], index: number, newIndex: number) { + assertsArrayIndex(array, index); + assertsArrayIndex(array, newIndex); + if (index === newIndex) { + return array; + } + const element = array[index]; + if (index < newIndex) { // Shift right + for (let iElement = index + 1; iElement <= newIndex; ++iElement) { + array[iElement - 1] = array[iElement]; + } + } else { // Shift left + for (let iElement = index; iElement !== newIndex; --iElement) { + array[iElement] = array[iElement - 1]; + } + } + array[newIndex] = element; + return array; +} diff --git a/cocos/core/data/utils/asserts.ts b/cocos/core/data/utils/asserts.ts index f89ef8ff00..df7c16d1d7 100644 --- a/cocos/core/data/utils/asserts.ts +++ b/cocos/core/data/utils/asserts.ts @@ -44,3 +44,7 @@ export function assertIsTrue (expr: boolean, message?: string) { throw new Error(`Assertion failed: ${message ?? ''}`); } } + +export function assertsArrayIndex (array: T[], index: number) { + assertIsTrue(index >= 0 && index < array.length, `Array index ${index} out of bounds: [0, ${array.length})`); +} diff --git a/tests/core/algorithm/move.ts b/tests/core/algorithm/move.ts new file mode 100644 index 0000000000..288242925a --- /dev/null +++ b/tests/core/algorithm/move.ts @@ -0,0 +1,23 @@ +import { move } from '../../../cocos/core/algorithm/move'; + +describe('Array utils', () => { + describe('Move', () => { + test('Location does not alters', () => { + expect(move([1, 2, 3], 0, 0)).toStrictEqual([1, 2, 3]); + }); + + test('Move right', () => { + expect(move([1, 2, 3], 0, 1)).toStrictEqual([2, 1, 3]); + expect(move([1, 2, 3], 0, 2)).toStrictEqual([2, 3, 1]); + expect(move([1, 2, 3, 4], 0, 2)).toStrictEqual([2, 3, 1, 4]); + expect(move([1, 2, 3, 4], 1, 2)).toStrictEqual([1, 3, 2, 4]); + }); + + test('Move left', () => { + expect(move([1, 2, 3], 1, 0)).toStrictEqual([2, 1, 3]); + expect(move([1, 2, 3], 2, 0)).toStrictEqual([3, 1, 2]); + expect(move([1, 2, 3, 4], 2, 0)).toStrictEqual([3, 1, 2, 4]); + expect(move([1, 2, 3, 4], 2, 1)).toStrictEqual([1, 3, 2, 4]); + }); + }); +}); \ No newline at end of file