Skip to content

Commit

Permalink
feat: add arrayMove function
Browse files Browse the repository at this point in the history
  • Loading branch information
Arcath committed Oct 6, 2021
1 parent 9fe020b commit 0878313
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/functions/array-move.spec.ts
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
])
})
})
25 changes: 25 additions & 0 deletions src/functions/array-move.ts
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[]
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down

0 comments on commit 0878313

Please sign in to comment.