Skip to content

Commit

Permalink
feat: add modulo function (#255)
Browse files Browse the repository at this point in the history
  • Loading branch information
ignatiusmb authored Aug 9, 2024
1 parent ef0adfe commit 4a9bff6
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
16 changes: 16 additions & 0 deletions workspace/mauss/src/math/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as math from './index.js';

const suites = {
'average/': suite('math/average'),
'modulo/': suite('math/modulo'),
};

suites['average/']('average base cases', () => {
Expand All @@ -14,4 +15,19 @@ suites['average/']('average numbers', () => {
assert.equal(math.average([10, 20, 30, 40, 50]), 30);
});

suites['modulo/']('modulo numbers', () => {
assert.equal(math.modulo(10, 0), NaN);

assert.equal(math.modulo(10, 3), 1);
assert.equal(math.modulo(-10, 3), 2);
assert.equal(math.modulo(10, -3), -2);
assert.equal(math.modulo(-10, -3), -1);
assert.equal(math.modulo(10, 5), 0);
assert.equal(math.modulo(-10, 5), 0);
assert.equal(math.modulo(10, -5), 0);
assert.equal(math.modulo(-10, -5), 0);
assert.equal(math.modulo(10, 1), 0);
assert.equal(math.modulo(10, 10), 0);
});

Object.values(suites).forEach((v) => v.run());
16 changes: 16 additions & 0 deletions workspace/mauss/src/math/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,19 @@ export function average(numbers: number[]): number {
export function clamp(min: number, max: number) {
return (value: number) => Math.max(min, Math.min(value, max));
}

/**
* The `%` is a remainder operator, this function computes the modulo operation and ensures a non-negative number for a non-negative divisor.
*
* @example
* ```javascript
* // returns 1
* modulo(5, 2);
*
* // returns 1
* modulo(-3, 2);
* ```
*/
export function modulo(a: number, n: number): number {
return ((a % n) + n) % n;
}

0 comments on commit 4a9bff6

Please sign in to comment.