Last Updated: February 25, 2016
·
416
· sukima

Rotating a number / array index

This is a super simple concept but often missed. Example problem set: You have a game with two or more players and the currentPlayer holds the state as an int. Normally when it's time to go to the next player a currentPlayer + 1 would do till you reached the last player and you get an index out of bounds error (currentPlayer => 3 when there are only two players). Normally a conditional to check out of bounds is do:

currentPlayer++;
if (currentPlayer >= numerOfPlayers) {
  currentPlayer = 0;
}

However, there is an easier way with the modulus. Since math is our friend, a modulus will convert your out of bounds into a rotating function. This is often the case for determining even odd values with an incrementing counter:

var i, isEven, results = [];
for (i = 0; i < 20; i++) {
  isEven = (i % 2) === 0;
  results.push(isEven);
}

If you reassign the counter to the result it's resetting that counter. This is equivalent to the first example:

currentPlayer = (currentPlayer + 1) % numberOfPlayers;
// Or for golf competitions:
c = ++c % n;

Using this technique and the poer of having an int for an array index the following code:

function playTurn(domElTile) {
  if (currentPlayer === 0) {
    domElTile.className = 'white';
    currentPlayer = 1;
  } else {
    domElTile.className = 'black';
    currentPlayer = 0;
  }
}

Can be simplified down to:

function playTurn(domElTile) {
  domElTile.className = ['white', 'black'][currentPlayer];
  currentPlayer = (currentPlayer + 1) % 2;
}

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside