How do you efficiently scroll an array with looping either acting on the array itself or returning a new array
arr = [1,2,3,4,5]
i want to do something like this:
arr.scroll(-2)
arr now is [4,5,1,2,3]
How do you efficiently scroll an array with looping either acting on the array itself or returning a new array
arr = [1,2,3,4,5]
i want to do something like this:
arr.scroll(-2)
arr now is [4,5,1,2,3]
 
    
    Use Array.slice:
> arr.slice(-2).concat(arr.slice(0, -2));
[4, 5, 1, 2, 3]
You can then generalize it and extend Array.prototype with the scroll function:
Array.prototype.scroll = function (shift) {
    return this.slice(shift).concat(this.slice(0, shift));
};
> arr.scroll(-2);
[4, 5, 1, 2, 3]
 
    
    