Skip to content

Instantly share code, notes, and snippets.

@damirm
Last active June 12, 2024 08:50
Show Gist options
  • Save damirm/18848ae9636abb524eb4 to your computer and use it in GitHub Desktop.
Save damirm/18848ae9636abb524eb4 to your computer and use it in GitHub Desktop.
Javascript shift array elements left/right by N positions
/**
* 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