Modulo operation

Benchmark created by Akim McMath on


Setup

function trunc(n) {
    n = +n;
  
    if (n !== n || n === 0 || n === -Infinity || n === Infinity) {
      return n;
    } else if (n < 0) {
      return Math.ceil(n);
    } else {
      return Math.floor(n);
    }
  }
  
  function opMod(a, n) {
    return +a % +n;
  }
  
  function truncMod(a, n) {
    a = +a;
    n = +n;
  
    return a - n * trunc(a / n);
  }
  
  function floorMod(a, n) {
    a = +a;
    n = +n;
  
    return a - n * Math.floor(a / n);
  }
  
  function euclidMod(a, n) {
    a = +a;
    n = Math.abs(+n);
  
    return a - n * Math.floor(a / n);
  }

Test runner

Ready to run.

Testing in
TestOps/sec
Modulo operator (truncated division)
opMod(4.25, 0.75);
opMod(4.25, -0.75);
opMod(-4.25, 0.75);
opMod(-4.25, -0.75);
ready
Truncated division
truncMod(4.25, 0.75);
truncMod(4.25, -0.75);
truncMod(-4.25, 0.75);
truncMod(-4.25, -0.75);
ready
Floored division
floorMod(4.25, 0.75);
floorMod(4.25, -0.75);
floorMod(-4.25, 0.75);
floorMod(-4.25, -0.75);
ready
Euclidean division
euclidMod(4.25, 0.75);
euclidMod(4.25, -0.75);
euclidMod(-4.25, 0.75);
euclidMod(-4.25, -0.75);
ready

Revisions

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

  • Revision 1: published by Akim McMath on