Last active
December 26, 2015 15:19
-
-
Save jasondscott/7172232 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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