DEV Community

Discussion on: Is JavaScript's .shift() Method a Performance Boost?

aminmansuri profile image
hidden_dude • Edited on

What's wrong with the obvious solution:

function rot(a) {
    let last = a[0]
    for (let i = 0; i < a.length; i++) {
        let next = (i+1) % a.length
        a[i] = a[next]
   a[a.length-1] = last
   return a;
Enter fullscreen mode Exit fullscreen mode

This is a straightforward O(n) solution.
Slice(), push() and all that are nice.. but won't a for loop do better in this case? (to avoid allocation issues)

savagepixie profile image

Well, your proposed solution only shifts the elements one place, while the challenge was to create a function that shifts them an undetermined number of places.

aminmansuri profile image

just change:

let next = (i+1) % a.length


let next = (i+offset) % a.length

Where offset is the number of spaces you want to shift.

Thread Thread
sh4bbi profile image
Shahnawaz Ansari

Your algorithm works for only 1 place shift, even with the edit you provided.

liaowow profile image
Annie Liao Author

Nothing wrong, it just wasn't on top of my head when I first approached the problem, especially applying the modulo operator, which was not an obvious/natural thought process for me. And somehow I didn't find that solution during my search. So thanks so much for sharing. Adding to my notes as we speak :)