Last active
November 10, 2018 13:36
-
-
Save lap00zza/187906a7999e672b2b5ab24fa6e5d028 to your computer and use it in GitHub Desktop.
Shift an array to left or right
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
// +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