Dev Helpers
← Back

Rotate without mutation

Rotate without mutation. A self-contained example using the JavaScript runtime.

Open this example in the interactive library

Source code

const rotate = (xs, n) => {
  if (!xs.length) return [];
  const k = ((n % xs.length) + xs.length) % xs.length;
  return [...xs.slice(k), ...xs.slice(0, k)];
};
console.log(rotate([1, 2, 3, 4], -1));

Sample output

[ 4, 1, 2, 3 ]