Hacker News new | ask | show | jobs
by ajayjain 4519 days ago
What does %% do? The documentation says: a %% b is the same as (a % b + b) % b, but what is the difference between "true mathematical modulo" and the standard modulo?
2 comments

The "standard modulo" is actually a remainder operator, and is a js-specific thing. Most languages implement the "true mathematical modulo", aka modulo.

One reason this is useful is if you want an array to wrap around. With modulo, you just index on `index % length` and all is well. But with remainder, this will only do what you want for `index >= 0`, because it can give negative outputs, given negative inputs.

I guess: -2 % 6 = -2, but -2 %% 6 = 4.
Yep. I think the name for it is true or Euclidean modulo. Here's the pull request that introduced it and two other new operators: https://github.com/jashkenas/coffee-script/pull/2887