mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-21 08:02:39 +08:00
Implements array.move() (#8790)
This commit is contained in:
committed by
GitHub
parent
ac09bea040
commit
0ddc51ac71
@@ -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<T> (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;
|
||||
}
|
||||
@@ -44,3 +44,7 @@ export function assertIsTrue (expr: boolean, message?: string) {
|
||||
throw new Error(`Assertion failed: ${message ?? '<no-message>'}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertsArrayIndex<T> (array: T[], index: number) {
|
||||
assertIsTrue(index >= 0 && index < array.length, `Array index ${index} out of bounds: [0, ${array.length})`);
|
||||
}
|
||||
|
||||
@@ -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]);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user