Infinite Arrays in JavaScript

-30 Oct 2014-

Recently I was working on an implementation of Conway’s Game of Life and I had to create an infinite grid made up of nested arrays. The problem that I soon ran into was hooking the Array’s first element to its last element, or tying it together so it looped.

I came up with the following helper function that will make an Array behave like a fixed length loop of values.

  return this.slice(index%this.length)[0];

This might look a little confusing to you, so I’ll break it down. First let me address the two goals of this function for it to successfully make an array infinite.

So the first thing to look here is the argument being passed into slice. This is index%this.length. The modulo remainder of the index and the length of the array (referenced by this while we are inside of this function) will be equal to the index that is passed in, unless it is greater than the index of the last element, in which case it will loop back to the beginning of the array. Look at the following example to understand.

var arr = [1,2,3];
// returns 2
// returns 0
// returns 1

The next piece of this puzzle is the slice function here. Slice returns an array of the array it is called from starting at the first argument with an optional length argument which we will not use. The reason we need slice is it already implements getting elements at indexes that are less than the first element’s index. For example, arr.slice(-1) will return a substring starting at the last value of the array. Since this return value for slice is an array, we need to take the first value, which will be the one we want, by adding [0] at the end.

The one concern here is that the function will never return undefined, which is what we want, but just something to be wary about when using it. You can’t check if a value exists at a certain index with this because it will always return a value in the array. Hope you find this useful and a few demonstrations of its behavior is below.

var arr = ['My','very','eager','mother'];

//returns 'My'
//returns 'mother'
//returns 'My'
//returns 'mother'
//returns 'eager'
//returns 'very'

Go back