Created
September 4, 2018 14:51
-
-
Save LucasPadovan/91fe548cccc35296325d5a3e6c67392f to your computer and use it in GitHub Desktop.
Shift an array left and 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
let items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']; | |
function shift({array, direction, amount}) { | |
let arr = array.slice(0); | |
let times = amount > arr.length ? amount % arr.length : amount; | |
let result = arr; | |
let modifier = direction === 'left' ? arr.length - times : times; | |
result = arr.concat(arr.splice(0, modifier)); | |
return result; | |
} | |
console.clear(); | |
console.log('shift right', shift({array: items, direction: 'left', amount: 1})); | |
console.log('shift left', shift({array: items, direction: 'right', amount: 1})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment