Skip to content

Commit

Permalink
Merge pull request #17 from giraugh/feat/rotateArray
Browse files Browse the repository at this point in the history
Add array rotation method
  • Loading branch information
GRA0007 authored May 21, 2023
2 parents 95c66ad + 164a560 commit ee27dfa
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/itchy-keys-tickle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@giraugh/tools": minor
---

Add array rotation method
1 change: 1 addition & 0 deletions lib/arrays/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export * from './range'
export * from './zipArrays'
export * from './zipArraysLongest'
export * from './partitionArray'
export * from './rotateArray'
36 changes: 36 additions & 0 deletions lib/arrays/rotateArray.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* Rotate the elements of an array by an amount specified.
* Essentially increments the index of every element by the amount,
* and elements at the end wrap round to the start.
* @param arr array to rotate
* @param amount number of elements to rotate by (default: 1)
* @returns the rotated array
*
* @example rotateArray([1, 2, 3]) === [3, 1, 2]
* @example rotateArray(['a', 'b', 'c'], -1) === ['b', 'c', 'a']
* @example rotateArray(['🍎', '🍐', '🍋'], 2) === ['🍐', '🍋', '🍎']
*/
export const rotateArray = <T>(arr: T[], amount: number = 1): T[] =>
arr.map((_, i) => arr[((( -amount + i ) % arr.length) + arr.length) % arr.length])


// Tests
if (import.meta.vitest) {
const { it, expect } = import.meta.vitest

it('works for example 1', () => {
expect(rotateArray([1, 2, 3])).toEqual([3, 1, 2])
})

it('works for example 2', () => {
expect(rotateArray(['a', 'b', 'c'], -1)).toEqual(['b', 'c', 'a'])
})

it('works for example 3', () => {
expect(rotateArray(['🍎', '🍐', '🍋'], 2)).toEqual(['🍐', '🍋', '🍎'])
})

it('works for amounts higher than the array length', () => {
expect(rotateArray(['a', 'b', 'c', 'd'], 6)).toEqual(['c', 'd', 'a', 'b'])
})
}

0 comments on commit ee27dfa

Please sign in to comment.