The MathUtils class provides a collection of utility methods for common mathematical operations, including rounding, percentages, GCD/LCM, clamping, and prime checks.
import { MathUtils } from '@brmorillo/utils';
// Calculate a percentage
const pct = MathUtils.percentage({ total: 200, part: 50 });
console.log(pct); // 25
// Find the greatest common divisor
const divisor = MathUtils.gcd({ a: 24, b: 36 });
console.log(divisor); // 12Rounds a number to the specified number of decimal places. decimals defaults to 2.
MathUtils.roundToDecimals({ value: 3.14159, decimals: 2 }); // 3.14Calculates the percentage of part relative to total. Throws if total is zero.
MathUtils.percentage({ total: 200, part: 50 }); // 25Generates a random number within a range. Throws if min is greater than max.
MathUtils.randomInRange({ min: 1, max: 10 }); // e.g., 5.432 (varies)Finds the greatest common divisor (GCD) of two integers. Uses Math.abs, so the result is always non-negative. Throws a ValidationError if either argument is not a finite integer.
MathUtils.gcd({ a: 24, b: 36 }); // 12
MathUtils.gcd({ a: -24, b: 36 }); // 12Finds the least common multiple (LCM) of two integers. Returns 0 if either argument is 0 (so lcm(0, 0) === 0), and uses Math.abs so the result is always non-negative. Throws a ValidationError if either argument is not a finite integer.
MathUtils.lcm({ a: 4, b: 6 }); // 12
MathUtils.lcm({ a: 0, b: 0 }); // 0Clamps a number within a specified range. If min is greater than max, the bounds are automatically swapped (consistent with NumberUtils.clamp).
MathUtils.clamp({ value: 10, min: 0, max: 5 }); // 5
MathUtils.clamp({ value: 3, min: 5, max: 0 }); // 3 (bounds auto-swapped)Checks if a number is prime. This is the canonical primality check for the
library; NumberUtils does not expose a duplicate. Throws a ValidationError
if value is not a finite integer.
MathUtils.isPrime({ value: 7 }); // true
MathUtils.isPrime({ value: 4 }); // falseimport { MathUtils } from '@brmorillo/utils';
// Reduce a fraction using GCD
const numerator = 24;
const denominator = 36;
const divisor = MathUtils.gcd({ a: numerator, b: denominator });
const reduced = {
numerator: numerator / divisor,
denominator: denominator / divisor
};
const ratio = MathUtils.percentage({ total: denominator, part: numerator });
console.log('Reduced:', reduced); // { numerator: 2, denominator: 3 }
console.log('Ratio:', MathUtils.roundToDecimals({ value: ratio })); // 66.67