Skip to content

Instantly share code, notes, and snippets.

@jahfer
Created December 18, 2012 05:15
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jahfer/4325251 to your computer and use it in GitHub Desktop.
Save jahfer/4325251 to your computer and use it in GitHub Desktop.
Sometimes you need to look ahead or behind the current element you're on when iterating through an array. This is a neat trick for doing that quickly, without stepping outside the bounds of your array.
var arr = ['a','b','c'];
// 1. LOOKING AHEAD
// -----------------------------
for (var i=0; i<arr.length; i++) {
var next = arr[ (i+1) % arr.length ]; // <= THE MAGIC
console.log(arr[i], "->", next);
}
/*
Output:
a -> b
b -> c
c -> a (important one)
*/
// 2. LOOKING BEHIND
// -----------------------------
// We have do to a bit more work to work with going backwards.
// Mod isn't well defined for negative numbers
// See: (http://en.wikipedia.org/wiki/Modulo_operation)
// Here's a hack for JS
Number.prototype.mod = function(n) {
return ((this % n) + n) % n;
}
// Now let's use it
for (var i=0; i<arr.length; i++) {
// Find the element before the current one
var prev = arr[ (i-1).mod(arr.length) ]; // <= MORE MAGIC
console.log(prev, "<-", arr[i]);
}
/*
Output:
c <- a (important one)
a <- b
b <- c
*/
@sunmockyang
Copy link

Is it possible that

 ((this % n) + n) % n

can be changed to

 (this + n) % n

@sunmockyang
Copy link

I come back to this gist once in a while. I now understand why you need ((this % n) + n) % n

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment