Explanation for Rotate Right

Question

Write a function rotateRight(array, num) that takes in an array and a number as args. The function should return a new array where the elements of the array are rotated to the right num times. The function should not mutate the original array and instead return a new array.

Define this function using function expression syntax.

HINT: you can use Array#slice to create a copy of an array


We are being asked for two things:

  1. To return an array with all the elements shifted over ‘num’ times.
  2. To NOT mutate the original array

Step 1. We need to start the function and create a variable to hold a COPY of our input array.

let rotateRight = function (array, num) {
  let result = array.slice(0);
};

Step 2. We need to create a for loop to tell our function how many times we want to rotate.

let rotateRight = function (array, num) {
  let result = array.slice(0);
  for (var i = 0; i < num; i++) {
    // some code here
  }
};

Step 3. We need to put some executable code within our for loop to be run during every cycle.

let rotateRight = function (array, num) {
  let result = array.slice(0);
  for (var i = 0; i < num; i++) {
    let ele = result.pop();
    result.unshift(ele);
  }
};

Step 4.

Now that our for loop has ended and our copied array looks just like how the answer looks, we need to output the answer.

let rotateRight = function (array, num) {
  let result = array.slice(0);
  for (var i = 0; i < num; i++) {
    let ele = result.pop();
    result.unshift(ele);
  }
  return result;
};

End Result

let rotateRight = function (array, num) {
  let result = array.slice(0);
  for (var i = 0; i < num; i++) {
    let ele = result.pop();
    result.unshift(ele);
  }
  return result;
};
let arr = ["a", "b", "c", "d", "e"];
console.log(rotateRight(arr, 2));
["d", "e", "a", "b", "c"];
console.log(arr);
["a", "b", "c", "d", "e"];
let animals = ["wombat", "koala", "opossum", "kangaroo"];
console.log(rotateRight(animals, 3));
["koala", "opossum", "kangaroo", "wombat"];
console.log(animals);
["wombat", "koala", "opossum", "kangaroo"];

Copy and paste it into an editor and see how it turns out!