I was wondering what was the most efficient way to rotate a JavaScript array.
I came up with this solution, where a positive n
rotates the array to the
I am not sure if this is the most efficient way but I like the way it reads, it's fast enough for most large tasks as I have tested it on production...
function shiftRight(array) {
return array.map((_element, index) => {
if (index === 0) {
return array[array.length - 1]
} else return array[index - 1]
})
}
function test() {
var input = [{
name: ''
}, 10, 'left-side'];
var expected = ['left-side', {
name: ''
}, 10]
var actual = shiftRight(input)
console.log(expected)
console.log(actual)
}
test()