Skip to main content
The Deno 2 Release Candidate is here
Learn more

modulo

modulo defines the mathematical modulo operation in TypeScript for Deno.
eibens/modulo on GitHub

Tag License deno doc CI Code coverage

Motivation

JavaScript has no native support for true modulo. The % operator works as modulo for positive numbers, but not negative ones. For example, -1 % 3 = -1 compared to 1 mod 3 = 2. If you need the latter, you can use this module, or you can memorize this formula:

n mod m = ((n % m) + m) % m

mod.ts

The modulo function calculates the modulo of a number n modulo m:

import { modulo } from "./mod.ts";

const n = 1;
const m = 3;
const p = modulo(n, m);
console.assert(p === 2);

The quotient function calculates the quotient q, which together with m and p defines the original value n:

import { modulo, quotient } from "./mod.ts";

const n = 1;
const m = 3;
const q = quotient(n, m);
const p = modulo(n, m);
console.assert(q * m + p === n);

The decompose function calculates both the quotient and modulo:

import { decompose } from "./mod.ts";

const n = 1;
const m = 3;
const [q, p] = decompose(n, m);
console.assert(q * m + p === n);