Skip to content

Instantly share code, notes, and snippets.

@lap00zza
Last active November 10, 2018 13:36
Show Gist options
  • Save lap00zza/187906a7999e672b2b5ab24fa6e5d028 to your computer and use it in GitHub Desktop.
Save lap00zza/187906a7999e672b2b5ab24fa6e5d028 to your computer and use it in GitHub Desktop.
Shift an array to left or right
// +by shift left
// -by shift right
const shiftArray = (arr, by) => {
const _by = (by | 0) % arr.length;
const rest = by > 0 ? arr.slice(0, _by) : arr.slice(_by);
return arr.map(
(_, i) => arr[i + _by] !== undefined
? arr[i + _by]
: rest.shift()
);
};
// Example:
// const arr = [1, 2, 3, 4]
// shiftArray(arr, 1) -> [2, 3, 4, 1]
// shiftArray(arr, 2) -> [3, 4, 1, 2]
// shiftArray(arr, -1) -> [4, 1, 2, 3]
// shiftArray(arr, -2) -> [3, 4, 1, 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment