This reversal method means you need to iterate all the way through your array twice, looking at 2 different parts of it at all times along the way. This is not the most efficient method whenever the array is big and the number of places to rotate is relatively small; it takes twice as much work and is probably less friendly on cpu caches.
In my browser, the following is faster for k = 1 whenever n > 25. When n gets to length of millions it is >10x faster.
function rotate(array, k = 1) {
const n = array.length;
if (k > 0) {
const start = array.slice(0, k);
for (let i = k; i < n; i++) array[i-k] = array[i];
array.splice(n-k, k, ...start);
}
else if (k < 0){
const end = array.slice(n+k);
for (let i = n + k - 1; i >= 0; i--) array[i-k] = array[i];
array.splice(0, -k, ...end);
}
return array;
}
If you want to do better, the same "overflow" array can be reused for every call:
rotate = {
const overflow = [];
return function rotate (array, k = 1) {
const n = array.length;
if (k > 0) {
for (let i = k-1; i >= 0; i--) overflow[i] = array[i];
for (let i = k; i < n; i++) array[i-k] = array[i];
for (let i = 1; i <= k; i++) array[n-i] = overflow[k-i];
}
else if (k < 0) {
for (let i = -k-1; i >= 0; i--) overflow[i] = array[n+k+i];
for (let i = n + k - 1; i >= 0; i--) array[i-k] = array[i];
for (let i = 0; i < -k; i++) array[i] = overflow[i];
}
return array;
}
}