angus-c / just

A library of dependency-free JavaScript utilities that do just one thing.

Home Page:https://anguscroll.com/just

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[just-rotate-right] Rotate array elements to the right

brandonmcconnell opened this issue · comments

It would be helpful to introduce a method to rotate array elements. Something this simple would do the trick:

Function definition

function rotateRight<T>(arr: T[], k: number): T[] {
  const mod = k % arr.length;
  return arr.slice(-mod).concat(arr.slice(0, -mod));
}

Usage

rotateRight([1, 2, 3],  1) // -> [3, 1, 2]
rotateRight([1, 2, 3], -1) // -> [2, 3, 1]
rotateRight([1, 2, 3],  2) // -> [2, 3, 1]