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:
NOT
mutate the original arrayStep 1. We need to start the function and create a variable to hold a COPY of our input array.
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);
}
};
['a', 'b', 'c', 'd', 'e'];
(how it looks like at the start)['e', 'a', 'b', 'c', 'd'];
(after one run of the for loop)['d', 'e', 'a', 'b', 'c'];
(after second/last run of the for loop)pop
’ off or remove our last element.
unshift
.
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;
};
return
line AFTER the for loop.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!