Design & Download
Your JS Library
in Seconds!!!

Snippet: mod() - Python Style Modulo

Written by Christopher West (cwest) on July 19, 2016.
Finds the remainder after dividing one number by another number while assuring that the remainder always carries the same sign as the divisor.
function mod(dividend, divisor) {
  return (dividend % divisor + divisor) % divisor;
}

mod(...) API Documentation

Finds the remainder after dividing one number by another number while assuring that the remainder always carries the same sign as the divisor.

Parameters

  1. dividend {number}:
    The number to be divided by the divisor.
  2. divisor {number}:
    The number to divide the dividend.

Returns

The remainder after dividing dividend by divisor. This value will always be between 0 (inclusive) and the divisor (non-inclusive).

Example

Mod by a positive integer:
console.log(YourJS.mod(7, 3));  // -> 1
console.log(YourJS.mod(6, 3));  // -> 0
console.log(YourJS.mod(5, 3));  // -> 2
console.log(YourJS.mod(4, 3));  // -> 1
console.log(YourJS.mod(3, 3));  // -> 0
console.log(YourJS.mod(2, 3));  // -> 2
console.log(YourJS.mod(1, 3));  // -> 1
console.log(YourJS.mod(0, 3));  // -> 0
console.log(YourJS.mod(-1, 3));  // -> 2
console.log(YourJS.mod(-2, 3));  // -> 1
console.log(YourJS.mod(-3, 3));  // -> 0
console.log(YourJS.mod(-4, 3));  // -> 2
Mod by a negative integer:
console.log(YourJS.mod(7, -3));  // -> -2
console.log(YourJS.mod(6, -3));  // -> -0
console.log(YourJS.mod(5, -3));  // -> -1
console.log(YourJS.mod(4, -3));  // -> -2
console.log(YourJS.mod(3, -3));  // -> -0
console.log(YourJS.mod(2, -3));  // -> -1
console.log(YourJS.mod(1, -3));  // -> -2
console.log(YourJS.mod(0, -3));  // -> -0
console.log(YourJS.mod(-1, -3));  // -> -1
console.log(YourJS.mod(-2, -3));  // -> -2
console.log(YourJS.mod(-3, -3));  // -> -0
console.log(YourJS.mod(-4, -3));  // -> -1
Mod by a positive floating point:
console.log(YourJS.mod(-2, 1.25));  // -> 0.5
console.log(YourJS.mod(-1, 1.25));  // -> 0.25
console.log(YourJS.mod(0, 1.25));  // -> 0
console.log(YourJS.mod(1, 1.25));  // -> 1
console.log(YourJS.mod(2, 1.25));  // -> 0.75
console.log(YourJS.mod(3, 1.25));  // -> 0.5
Mod by a negative floating point:
console.log(YourJS.mod(-2, -1.25));  // -> -0.75
console.log(YourJS.mod(-1, -1.25));  // -> -1
console.log(YourJS.mod(0, -1.25));  // -> -0
console.log(YourJS.mod(1, -1.25));  // -> -0.25
console.log(YourJS.mod(2, -1.25));  // -> -0.5
console.log(YourJS.mod(3, -1.25));  // -> -0.75