Hey just to point out that shift itself is a bit of a pain doing it frequently - that's because a shift "might" have to move all of the elements in the array (it's not allocating fortunately) - it depends on the actual engine implementation - but it's likely.
push and pop are very fast operations because they only change the length of the array, unshift and shift have to move all of the items in the array (because the operate at the beginning). So depending on what you are doing it might be wise to reverse and array and operate at the end - really would have to be a lot of operations though.
In the case of a rotate you can use the fact that .splice returns the items it removes so rotateLeft to me looks like:
Thanks Mike for pointing out the potential costly operation of shift -- I read somewhere that also compared shift with push and pop, but your explanation makes more sense to me. And yes, using splice first and adding the specific items to the array via spread operator does look more efficient. Really appreciate your help! :)
Hey just to point out that
shift
itself is a bit of a pain doing it frequently - that's because a shift "might" have to move all of the elements in the array (it's not allocating fortunately) - it depends on the actual engine implementation - but it's likely.push
andpop
are very fast operations because they only change the length of the array,unshift
andshift
have to move all of the items in the array (because the operate at the beginning). So depending on what you are doing it might be wise to reverse and array and operate at the end - really would have to be a lot of operations though.In the case of a
rotate
you can use the fact that.splice
returns the items it removes sorotateLeft
to me looks like:Effectively push on the end the items you removed from the front. The cost of this is an array the size of the items you removed. But no loop.
Thanks Mike for pointing out the potential costly operation of
shift
-- I read somewhere that also comparedshift
withpush
andpop
, but your explanation makes more sense to me. And yes, usingsplice
first and adding the specific items to the array via spread operator does look more efficient. Really appreciate your help! :)Yeah we can do it without spread - but now it looks nicer in ES6 :)
It looks like you could get better perf (at least for long arrays) using
Array#concat
without the spread operator:jsperf.com/concat-vs-spreader
Also remember that
Array#push
returns thepushed itemnew length of the array, not the array 😉You're right, should have a
, array
at the end I guess or a separate line