diff --git a/src/functions/array-move.spec.ts b/src/functions/array-move.spec.ts new file mode 100644 index 0000000..2e9dd0e --- /dev/null +++ b/src/functions/array-move.spec.ts @@ -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 + ]) + }) +}) diff --git a/src/functions/array-move.ts b/src/functions/array-move.ts new file mode 100644 index 0000000..5ea47e2 --- /dev/null +++ b/src/functions/array-move.ts @@ -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 = ( + 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[] +} diff --git a/src/index.ts b/src/index.ts index e82b5e3..4c58cbe 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,7 @@ export {BitMask} from './classes/bit-mask' export {Logger} from './classes/logger' +export {arrayMove} from './functions/array-move' export {asyncForEach} from './functions/async-for-each' export {asyncMap} from './functions/async-map' export {