As for 'my console.log shows a different value than what my function is returning', your code is working correctly. The value returned and the value inside are same on console.log()
var rotate = function(nums, k) {
let n=0
let temp = []
let l =nums.length
k=k%l
let x = JSON.parse(JSON.stringify(nums))
while(n<k){
let last = x[l-1]
for(let i=1;i<l;i++){
temp[i] = x[i-1]
}
temp[0]=last
x=JSON.parse(JSON.stringify(temp))
n++
}
console.log("before return: ", x)
return x
};
const rotated = rotate([1,2,3,4,5,6,7], 3)
console.log(rotated)
But as you say 'it is not the best solution'. You can find some good algorithms on the internet to make it efficient. If you are doing these tasks to learn javascript rather than diving into algorithms, you can rewrite this function using some array methods. Check out this code:
const rotateAfter = (nums, k) => {
const leftSide = nums.slice(0, k+1)
const rightSide = nums.slice(k+1, nums.length)
return rightSide.concat(leftSide)
}
const rotatedArray = rotateAfter([1,2,3,4,5,6,7], 3)
console.log(rotatedArray)
It splits the array into two parts: left and right using Array.slice()
method. Then reurns them is inverse order. Such a simple solution.
***Edit: ***
The second algorithm you provided in the comment is working fine. But it is slow as it uses a loop. Imagine the situation you perform this alogrithm on an array of 1000 users data. It slows down the performance.
You can edit the function I suggested to manipulate the given array rather than returning a new one. It is much faster. I created a speed testing environment in Node.js. Then performed some speed tests on a list of actual 400 posts data. The results show that the algorithm I suggested was roughly 3.624 times faster than the one with a loop. See here:
const posts = [
// ..... 400
{
"userId": 10,
"id": 199,
"title": "numquam repellendus a magnam",
"completed": true
},
// .....
]
var algorithm1 = function(nums, k) {
const started = present()
let n=0;
let l= nums.length;
k=k%l;
let temp = [];
while(n<k){
temp.unshift(nums.pop());
n++
}
nums.unshift(...temp)
console.log("alg1 took: ", present()-started)
};
const algorithm2 = (nums, k) => {
const started = present()
const leftSide = nums.slice(k+1, nums.length)
nums.splice(k+1, nums.length-1)
nums.unshift(...leftSide)
console.log("alg2 took: ", present()-started)
}
algorithm1(posts, 275)
algorithm2(posts, 275)
// note that it only works in node.js environment
Results:
alg1 took: 0.21170002222061157
alg2 took: 0.06599998474121094
running ...
alg1 took: 0.20789998769760132
alg2 took: 0.06470000743865967
running ...
alg1 took: 0.19339996576309204
alg2 took: 0.025599956512451172
running ...
alg1 took: 0.21679997444152832
alg2 took: 0.12199997901916504
running ...
alg1 took: 0.2791000008583069
alg2 took: 0.05779999494552612
running ...
alg1 took: 0.3149999976158142
alg2 took: 0.05210000276565552
running ...
alg1 took: 0.2116999626159668
alg2 took: 0.06309998035430908