Last active
June 12, 2024 08:50
-
-
Save damirm/18848ae9636abb524eb4 to your computer and use it in GitHub Desktop.
Javascript shift array elements left/right by N positions
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
/** | |
* Fast method | |
*/ | |
function shift(arr, direction, n) { | |
var times = n > arr.length ? n % arr.length : n; | |
return arr.concat(arr.splice(0, (direction > 0 ? arr.length - times : times))); | |
} | |
/** | |
* Slow method | |
*/ | |
function shift2(arr, direction, n) { | |
for (var i = n; i > 0; --i) { (direction > 0 ? arr.unshift(arr.pop()) : arr.push(arr.shift())); } | |
return arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment