This solution is branchless, but performs %
twice:
function wrapIndex(i, i_max) {
return ((i % i_max) + i_max) % i_max;
}
It should be said the C#/Java behavior of %
is assumed, i.e. the result has the same sign as the dividend. Some languages define the remainder calculation to take the sign of the divisor instead (e.g. mod
in Clojure). Some languages have both variants (mod
/rem
pair in Common Lisp, Haskell, etc). Algol-68 has %x
which always returns a non-negative number. C++ left it up to implementation until C++11, now the sign of the remainder is (almost) fully specified according to the dividend sign.
See also
- Wikipedia/Modulo operation