DEV Community

loading...

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

Collapse
bpedroza profile image
Bryan • Edited

Nice write up. Thanks for sharing.

Another solution could use slice along with the spread operator:

function rotate(array, num) {
  const size = array.length;

  if(num === 0 || num === size) {
    return array;   
  }

  if(num < 0) {
    num = size + num;
  }

  if(num > size) {
     num = num - size;
  }

  return [
    ...array.slice((num * -1), size),
    ...array.slice(0, size - num)
  ];
}