Since you have infinite levels, I would suggest a structure similar to what you already have, with a little customization.
Instead of storing everything in one large array and moving things inside this array every time the user moves (ouch), instead, 9 fragments of the map (each of which is approximately equal to twice the size of the screen) are stored when the user approaches the edge of the current piece, delete the pieces that are off the screen, move all the pieces to the left and load new ones in the gap.
Hope this was clear, but just in case, here's a diagram:

The letter squares are the pieces of the map, and the red square is the viewport (I drew it a bit, I remember that the viewport is smaller than the black squares). As the viewport moves to the right, you unload pieces AB and C, move all the others to the left, and load new data to the right. Since the piece is twice the width of the screen, you have the time it takes the user to cross the screen to generate / load a level into these pieces. If the user moves quickly around the world, you may have a set of 4x4 pieces for extra buffering.
To return to previous map fragments. There are several ways to do this:
- Write fragments to your hard drive when they are no longer in use (or something similar in javascript)
- Expand your piece, set endlessly in memory. Instead of an array of pieces, there is an auxiliary array that takes the x / y position of the piece and returns a piece (or zero, which indicates that the user has never been here before, and you need to generate it).
- Generate your levels procedurally, this is difficult, but means that after a piece is disconnected from the screen, you can simply dispose of it and be sure that you can restore the same piece again later.
Martin
source share