How can I generate a circular array of values in JavaScript?
When working with arrays in JavaScript, it's common to need a way to cycle through elements repeatedly, creating a circular pattern. This is useful in many scenarios, such as rotating banners, round-robin scheduling, or repeating sequences in animations. One common question in tech interviews is how to generate or access an array in a circular way, especially when the index exceeds the array length.
A circular array means that once you reach the end of the array, you loop back to the beginning. For example, if you have an array [1, 2, 3]
, accessing index 4 should return 2 because after 3, it wraps around to the beginning.
How to generate a circular array in JavaScript?
One straightforward way to handle this is to use the modulo (%
) operator. The modulo operator returns the remainder of the division of two numbers. This makes it perfect for wrapping around indices in an array.
Suppose you have an array:
Javascript
You can create a function that takes an index and returns the corresponding value in a circular manner:
Javascript
Using this function:
Javascript
Here, the index % array.length
ensures that no matter how large the index is, it wraps back to a valid position within the array.
Handling negative indices
In some cases, you might want to support negative indices, which are common in some languages for accessing elements from the end of the array. To handle negative indices properly, modify the function:
Javascript
This way, negative indices also wrap around:
Javascript
Using an iterator for circular access
If you want to iterate over the array in a circular way repeatedly, you can create a generator:
Javascript
Using the generator:
Javascript
This approach makes it easy to fetch the next element in a circular pattern repeatedly.