Last active
September 9, 2016 20:41
-
-
Save aubergene/7ecfe624199e68f60258 to your computer and use it in GitHub Desktop.
underscore array rotate
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
/** | |
* Underscore function to rotate an array | |
* See also _.cycle https://gist.github.com/901648 | |
* | |
* _.rotate([1, 2, 3, 4, 5]); | |
* => [2, 3, 4, 5, 1] | |
* _.rotate([1, 2, 3, 4, 5], 3); | |
* => [4, 5, 1, 2, 3] | |
* _.rotate([1, 2, 3, 4, 5], -3); | |
* => [3, 4, 5, 1, 2] | |
* _.rotate([1, 2, 3, 4, 5], 6); | |
* => [2, 3, 4, 5, 1] | |
*/ | |
_.mixin({ | |
rotate: function(array, n, guard) { | |
var head, tail; | |
n = (n == null) || guard ? 1 : n; | |
n = n % array.length; | |
tail = array.slice(n); | |
head = array.slice(0, n); | |
return tail.concat(head); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment