Skip to content

Instantly share code, notes, and snippets.

@LucasPadovan
Created September 4, 2018 14:51
Show Gist options
  • Save LucasPadovan/91fe548cccc35296325d5a3e6c67392f to your computer and use it in GitHub Desktop.
Save LucasPadovan/91fe548cccc35296325d5a3e6c67392f to your computer and use it in GitHub Desktop.
Shift an array left and right
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