wrap-around
Restricts a number n
to the interval 0 <= n < m
by "wrapping it around" within said range.
const wrap = var result = {}for var m = 3 n = -3; n < 9; n++ resultn =
Some possible uses of this function include:
- restricting an index to valid array indices
index =
- selecting items from the end of a list (Python-style!)
> var array = 'foo' 'bar' 'baz'> array'baz'
- wrapping the player around the screen in a game of Pac-Man, Snake, etc.
heroposition =
usage
n % m
?
Why not just use While the modulo operator wraps positive values with ease (it's actually used internally by the wrap
function), it takes a bit more setup to handle negative values correctly. Consider the following example, in which %
fails to provide the desired result:
> -1 % 3-1 > 2
What about loops?
Using loops for this kind of thing is a handy way of demonstrating what exactly this function does - wrap(m, n)
produces the same result as two loops forcing a number between the desired range.
while n < 0 n += mwhile n >= m n -= m
Unfortunately, they're also 300x slower. 😬
# wrap 100000 timesok ~4.7 ms (0 s + 4696167 ns) # loop 100000 timesok ~1.36 s (1 s + 359910028 ns)
So at the end of the day, you're better off avoid loops for "wrapping" numbers in production code. Use the modulo %
operator for positive numbers or wrap-around
if you plan on handling negative numbers.