DEV Community

loading...

Discussion on: Not an "Easy" Algorithm: Rotating an Array, Three Ways

Collapse
jpantunes profile image
JP Antunes

Nice post! I have two solutions, neither of which is better than yours, but still might be interesting.

Approach 1: Functional style, easy to read but slow

const head = (arr, k) => arr.slice(0, k);
const tail = (arr, k) => arr.slice(k);
const rotator = (arr, k) => [...tail(arr, k), ...head(arr, k)];

Approach 2: using recursion and modifying the array in place

const recursed = (arr, k) => k == 0 ? arr : (arr.push(arr.shift()) , recursed(arr, --k));