Reputation: 391
I am trying to write a function that takes an array and returns a new array with all elements shifted n indices to the left. For example:
rotLeft([1,2,3,4],2)
// should return [3,4,1,2]
I wrote a recursive function that removes the value at index 0 and assigns it to last index using .shift() and .push().
const rotLeft = (array, n) => {
console.log(array, n); // <-- this prints out expected array
if (!n) return array; // <-- but this returns undefined! :(
array.push(array.shift());
rotLeft(array, n - 1);
};
console.log(rotLeft([1, 2, 3, 4, 5, 6, 7], 9));
How come each console.log(array) prints out the expected array but the array is undefined when the function returns?
Upvotes: 3
Views: 492
Reputation: 2032
Or you can use Array.prototype.slice() to archive this
const arr = [1,2,3,4]
const rotLeft = (arr, n) => arr.slice(n).concat(arr.slice(0,n))
const tmp1 = rotLeft(arr, 2)
const tmp2 = rotLeft(arr, 3)
console.log("tmp1", tmp1)
console.log("tmp2", tmp2)
Upvotes: 0
Reputation: 44107
You need to return
the recursive call.
const rotLeft = (array, n) => {
if (!n) return array;
array.push(array.shift());
return rotLeft(array, n - 1);
};
console.log(rotLeft([1, 2, 3, 4, 5, 6, 7], 9));
Upvotes: 0
Reputation: 22776
You are not returning the rotated array (for each recursive call), you need another return
for rotLeft(array, n - 1)
:
const rotLeft = (array, n) => {
// console.log(array, n);
if (!n) return array;
array.push(array.shift());
return rotLeft(array, n - 1); // <-- return the rotated array (recursively)
};
console.log(...rotLeft([1, 2, 3, 4, 5, 6, 7], 2));
Even shorter (with concat
and the ternary operator):
const rotLeft = (array, n) => {
return n ? rotLeft(array.concat([array.shift()]), n - 1) : array;
};
console.log(...rotLeft([1, 2, 3, 4, 5, 6, 7], 2));
Upvotes: 1
Reputation: 629
Try this code below. You are not returning the results from function. I just added the return statement
const rotLeft = (array, n) => {
//console.log(array, n); // <-- this prints out expected array
if (!n) return array; // <-- but this returns undefined! :(
array.push(array.shift());
return rotLeft(array, n - 1);
};
Usage: rotLeft([1,2,3,4],2)
Upvotes: 0