Created
April 1, 2015 21:44
-
-
Save isRuslan/9618c8d568cf58375f12 to your computer and use it in GitHub Desktop.
JS: rotate array with N
This file contains hidden or 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
/** | |
* 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] ); |
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
You didn't pass n in the example