All files / math / modulo.ts

100.00% Branches 5/5
100.00% Lines 9/9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x3
x159
x159
x203
x159
x306
x306
x159
x159





























// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

/**
 * Computes the floored modulo of a number.
 *
 * @param num The number to be reduced
 * @param modulus The modulus
 * @returns The reduced number
 *
 * @example Usage
 * ```ts
 * import { modulo } from "@std/math/modulo";
 * import { assertEquals } from "@std/assert";
 *
 * for (let n = -3; n <= 3; ++n) {
 *  const val = n * 12 + 5;
 *  // 5 o'clock is always 5 o'clock, no matter how many twelve-hour cycles you add or remove
 *  assertEquals(modulo(val, 12), 5);
 * }
 * ```
 */
export function modulo(num: number, modulus: number): number {
  num %= modulus;
  if (num === 0) {
    num = modulus < 0 ? -0 : 0;
  } else if ((num < 0) !== (modulus < 0)) {
    num += modulus;
  }
  return num;
}