Modulo for Negative Numbers

JavaScript performance comparison

Test case created by Hugh Kennedy

Preparation code

<script>
function modulo_a(x, y) {
  return (((x % y) + y) % y)
}

function modulo_b(x, y) {
  var n = x % y;
  return n < 0 ? (y + n) : n
}

function modulo_c(x, y) {
  if (x > 0) return x % y
  x += (~~(x / y) + 1) * y
  return x % y
}
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
A
modulo_a( 100, 10)
modulo_a(-100, 10)
pending…
B
modulo_b( 100, 10)
modulo_b(-100, 10)
pending…
C
modulo_c( 100, 10)
modulo_c(-100, 10)
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment