Mr Speaker


Warning: count(): Parameter must be an array or an object that implements Countable in /home/mrspeak/public_html/wp-content/themes/stuartspeaker/functions.php on line 24

Warning: count(): Parameter must be an array or an object that implements Countable in /home/mrspeak/public_html/wp-content/themes/stuartspeaker/functions.php on line 27

Warning: count(): Parameter must be an array or an object that implements Countable in /home/mrspeak/public_html/wp-content/themes/stuartspeaker/functions.php on line 29

One-line array wrap

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!


Warning: count(): Parameter must be an array or an object that implements Countable in /home/mrspeak/public_html/wp-content/themes/stuartspeaker/functions.php on line 33
Captcha! Please type 'radical' here: *
How did you find this thingo? *