Repository
Current version released
5 years ago
modulo
modulo defines the mathematical modulo operation in TypeScript for Deno.
— eibens/modulo on GitHub
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 either use this
module, or memorize this modulo formula for JavaScript:
n mod m = ((n % m) + m) % mmod.ts
The modulo function calculates p = n mod m:
import { modulo } from "./mod.ts";
const n = -1;
const m = 3;
const p = modulo(n, m);
const test = p === 2;
if (!test) throw new Error();The quotient function calculates q = floor(q / m).
import { modulo, quotient } from "./mod.ts";
const n = -1;
const m = 3;
const q = quotient(n, m);
const test = q === -1;
if (!test) throw new Error();The decompose function calculates (q, p). q, m, and p together
define the original value n = q * m + p:
import { decompose } from "./mod.ts";
const n = -1;
const m = 3;
const [q, p] = decompose(n, m);
const test = n == q * m + p;
if (!test) throw new Error();