Skip to content

Instantly share code, notes, and snippets.

@isRuslan
Created April 1, 2015 21:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save isRuslan/9618c8d568cf58375f12 to your computer and use it in GitHub Desktop.
Save isRuslan/9618c8d568cf58375f12 to your computer and use it in GitHub Desktop.
JS: rotate array with N
/**
* Write a function that takes an array of integers
and returns that array rotated by N positions.
For example, if N=2, given the input array [1, 2, 3, 4, 5, 6]
the function should return [5, 6, 1, 2, 3, 4]
*/
var rotate = function (arr, n) {
var L = arr.length;
return arr.slice(L - n).concat(arr.slice(0, L - n));
};
console.assert( rotate( [1, 2, 3, 4, 5, 6] ), [5, 6, 1, 2, 3, 4] );
@spinalwiz
Copy link

You didn't pass n in the example

@iamaaviral
Copy link

Above Code fails for value of n >= 13. We must use n% arr.length for such cases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment