Skip to content

Instantly share code, notes, and snippets.

@unyo
Last active January 20, 2017 00:24
Show Gist options
  • Save unyo/2a1c6d260bc1e23590ef4b98642096cb to your computer and use it in GitHub Desktop.
Save unyo/2a1c6d260bc1e23590ef4b98642096cb to your computer and use it in GitHub Desktop.
Wrapping array index snippet
// Here is an easy way to increment / decement an index by any amount and get the correct value if you were in an infinite / wrapping array
var x = [0, 1, 2, 3, 4] // this is the wrapping array we want
var n = x.indexOf(0) // this is the index
n++ // now you increment or decment, by any amount
var val = x[(n>=0)?n%x.length:x.length+n] // this is the magic wrapping sauce
console.log(val==1)// true
n = -1
val = x[(n>=0)?n%x.length:x.length+n]
console.log(val==4)
n = -2
val = x[(n>=0)?n%x.length:x.length+n]
console.log(val==3)
n = 5
val = x[(n>=0)?n%x.length:x.length+n]
console.log(val==0)
n = 6
val = x[(n>=0)?n%x.length:x.length+n]
console.log(val==1)
n = -6 // it doesn't account for going back past the length of the array though, so be aware of this limitation
val = x[(n>=0)?n%x.length:x.length+n] // n = -5 results in val = 0
console.log(val==4) // false, val is undefined as it's trying to access x[-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment