Skip to content

Instantly share code, notes, and snippets.

@aubergene
Last active September 9, 2016 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aubergene/7ecfe624199e68f60258 to your computer and use it in GitHub Desktop.
Save aubergene/7ecfe624199e68f60258 to your computer and use it in GitHub Desktop.
underscore array rotate
/**
* 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