Under 1 kb gzipped
Drop it into dashboards, data scripts, or static pages without adding meaningful weight to your bundle.
01 · Why it exists
Math and a full library.The native Math object covers basic operations: rounding, trigonometry, powers. But statistical aggregates, percentile lookups, number theory basics like GCD and LCM, and safe clamping keep appearing in application work without native solutions.
The common workarounds are writing those helpers inline again and again, or pulling in a large library that brings far more surface area than needed. Maths.js sits between those extremes: small enough to drop anywhere, complete enough to cover the methods that actually come up, and strict enough to throw clear errors instead of silently returning NaN.
Core features
Drop it into dashboards, data scripts, or static pages without adding meaningful weight to your bundle.
Every method throws a typed TypeError or RangeError with a clear message instead of silently returning NaN.
Works in the browser via <script> tag or in Node.js via require(). No build step, no transitive packages.
02 · Installation
npm
npm install @peterbenoit/mathsjs
CDN (jsDelivr)
<script src="https://cdn.jsdelivr.net/npm/@peterbenoit/mathsjs/Maths.js"\\></script>
Node.js
const Maths = require('@peterbenoit/mathsjs');
Maths.avg(10, 20, 30); // 20
Maths.median(7, 1, 4); // 4
Maths.gcd(48, 18); // 6
Attaches to globalThis.Maths in browser contexts. No bundler or build step needed.
03 · API reference
Maths.Aggregation
| Method | Description | Returns |
|---|---|---|
avg(...values) | Arithmetic mean | number |
sum(...values) | Total of all values | number |
Statistics
| Method | Description | Returns |
|---|---|---|
median(...values) | Middle value; mean of two middle for even-length inputs | number |
mode(...values) | Most frequent value(s); null when all are unique | number[] | null |
range(...values) | Difference between max and min | number |
percentile(values, p) | Value at the pth percentile (0–100) | number |
Number Theory
| Method | Description | Returns |
|---|---|---|
factorial(n) | Product of all positive integers up to n | number |
gcd(a, b) | Greatest common divisor | number |
lcm(a, b) | Least common multiple | number |
Utility
| Method | Description | Returns |
|---|---|---|
clamp(value, min, max) | Constrains a value to the range [min, max] | number |
distance(x1, y1, x2, y2) | Euclidean distance between two 2D points | number |
04 · Examples
Statistics
Maths.avg(10, 20, 30); // 20
Maths.median(1, 3, 2); // 2
Maths.mode(1, 2, 2, 3); // [2]
Maths.percentile([1,2,3,4,5], 90); // 5
Number theory
Maths.factorial(5); // 120
Maths.gcd(48, 18); // 6
Maths.lcm(4, 6); // 12
Utility
Maths.clamp(12, 0, 10); // 10
Maths.distance(0, 0, 3, 4); // 5
MIT licensed. Available on npm and jsDelivr. Built-in test suite using Node's native test runner.
Keep exploring