In Javascript, what is the most compact, elegant and efficent way to bring the last element of an array to the beginning?

I'm programming a Snake game

and the logic of the snake's movement dictates that if I have a Javascript array

var links = [elem_0, elem_1, ..., elem_n];

of elements representing links of the snake, then the way for the snake to move is to pop out elem_n, change its position to be that of the elem_0 plus the translation units dx and dy, and then put it at the beginning of the array:

[elem_0, elem_1, ..., elem_n] ---> [elem_n, elem_0, ..., elem_(n-1)]

(with some internal properties of elem_n changed in the process)

What is the way to do this that makes no compromise between

  • optimally efficient in number of operations and memory usage
  • readable
  • maintainable
  • clever (optional)
  • elegant
  • compact

????

Answers


optimally efficient in number of operations and memory usage

You're asking for two optimisations that usually counter one another. e.g. more speed == more memory.

That said, I'd probably choose a (doubly) linked list to store my snake, because removal or addition at the front or tail are very cheap, and with games, faster is way preferable to less memory (within reason, but I wonder how long your snake would have to be before you run into memory issues... well beyond what's playable... and some).

Of course, I assume you've measured and found the standard array based methods to be too slow (seems unlikely).


You can rotate an array in two ways :

links.unshift(links.pop());   or

links.push(links.shift());

first method solves your issue.


For any version of Javascript from ES3 forward:

links.unshift(links.pop());

Need Your Help

Converting PHP Contact Form to SMTP

php html forms email smtp

had alot fo problems making a functional contact form tonight. After messing for hours i finally found out that i can only use SMTP with my web hoster.

Flash / actionscript 3 sound delay

flash actionscript-3 audio delay

Im working on a flash project where I am loading multiple sounds from external files. The problem is that when I play them within my project there is a small delay from when they should be played u...