-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import {arrayMove} from '../index' | ||
|
||
describe('Array Move', () => { | ||
it('should move objects in an array', () => { | ||
const a = [1, 2, 3, 4, 5, 6] | ||
|
||
const b = arrayMove(a, 1, 2) | ||
expect(b).toStrictEqual([1, 3, 2, 4, 5, 6]) | ||
expect(a).toStrictEqual([1, 2, 3, 4, 5, 6]) // We don't want to effect the original array | ||
|
||
const c = arrayMove(a, 1, 10) | ||
expect(c).toStrictEqual([ | ||
1, | ||
3, | ||
4, | ||
5, | ||
6, | ||
undefined, | ||
undefined, | ||
undefined, | ||
undefined, | ||
undefined, | ||
2 | ||
]) | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
/** | ||
* Move an index to another within the given array. | ||
* | ||
* @param originalArray The array to move objects in. | ||
* @param oldIndex The index to move. | ||
* @param newIndex The index to move the entry to. | ||
* @returns The array with the elements moved. | ||
*/ | ||
export const arrayMove = <T>( | ||
originalArray: T[], | ||
oldIndex: number, | ||
newIndex: number | ||
): T[] => { | ||
const array: (T | undefined)[] = [...originalArray] | ||
|
||
if (newIndex >= array.length) { | ||
let key = newIndex - array.length + 1 | ||
while (key--) { | ||
array.push(undefined) | ||
} | ||
} | ||
array.splice(newIndex, 0, array.splice(oldIndex, 1)[0]) | ||
|
||
return array as T[] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters