DEV Community

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

Collapse
 
aminmansuri profile image
hidden_dude • Edited

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)

Collapse
 
liaowow profile image
Annie Liao

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 :)

Collapse
 
savagepixie profile image
SavagePixie

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.

Collapse
 
aminmansuri profile image
hidden_dude

just change:

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

to

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.