Skip to content

Instantly share code, notes, and snippets.

@jasondscott
Last active December 26, 2015 15:19
Show Gist options
  • Save jasondscott/7172232 to your computer and use it in GitHub Desktop.
Save jasondscott/7172232 to your computer and use it in GitHub Desktop.
/* Rotate an array n positions
* if n is positive - rotate to the left
* if n is negative - rotate to the right
*/
Array.prototype.rotate = function(n) {
//Make a copy of the current array
var newArray = this.slice(0);
//Handle a number greater than the length so that it loops around
if (n > this.length) n = (n/Math.abs(n)) * (n % this.length);
var a = newArray.splice(n);
return a.concat(newArray);
};
var a = [1,2,3,4,5,6];
var b = a.rotate(-2);
console.log(a);
console.log(b);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment