I like this lil' one-liner for wrapping around an array forward, or backwards. Given an array, with a current index, you want to move either to the next item, or the previous one. Here's the setup:
var a = ["alice", "bob", "charlie"],
current = 0; // start with "alice",
direction = Math.random() < 0.5 ? -1 : 1;
The direction is picked at random. To find the nth + 1
, or nth - 1
, we use modulus... plus a trick:
current = (current + direction + a.length) % a.length;
See the trick? Modulus will always return us the correct value when incrementing - but when decrementing: -1 % a.length = -1
. To fix this, we always add the array length before taking the modulus. The value will never be less than 0. Nifty!