Collection · 22 utilities

Number utilities

Small numeric transformations with explicit validation and floating-point caveats. These are not financial arithmetic policies.

Clamp a number to a range

Keep a number inside an inclusive minimum and maximum.

function clamp({ value, min, max }) { return Math.min(max, Math.max(min, value)); }number

Round to a number of digits

Apply decimal scaling and JavaScript rounding for display-oriented values.

function roundTo({ value, digits }) { const factor = 10 ** digits; return Math.round(value * fa…number

Add an ordinal suffix to a number

Append st, nd, rd or th to a positive integer.

function addOrdinal(n) { return `${n}${['st', 'nd', 'rd'][((((n + 90) % 100) - 10) % 10) - 1] |…number

Calculate Fibonacci numbers

Return the nth Fibonacci number with memoized recursion.

function fibonacci(n, memo = {}) { return memo[n] || (n <= 2 ? 1 : (memo[n] = fibonacci(n - 1, …number

Calculate the division of numbers

Divide the first number by each of the others in turn.

function division(values) { return values.reduce((a, b) => a / b); }number

Subtract numbers

Subtract each number from the first in turn.

function subtract(values) { return values.reduce((a, b) => a - b); }number

Convert a number to equivalent characters

Turn a zero-based index into a spreadsheet-style column name.

function toChars(n) { return `${n >= 26 ? toChars(Math.floor(n / 26) - 1) : ''}${'ABCDEFGHIJKLM…number

Multiply numbers

Multiply numbers from left to right.

function multiply(values) { return values.reduce((a, b) => a * b); }number

Convert decimal to binary recursively

Build the binary digits of a non-negative integer as a decimal-looking number.

function decToBinary(num) { return num === 0 ? 0 : (num % 2) + 10 * decToBinary(Math.floor(num …number

Prefix an integer with zeros

Pad a non-negative integer to a given width.

function prefixWithZeros({ n, length }) { return String(n).padStart(length, '0'); }number

Wrap a number between two values

Map a number into [min, max) like an angle or a carousel index.

function wrap({ num, min, max }) { return ((((num - min) % (max - min)) + (max - min)) % (max -…number

Try a function in the local code lab, then read its limits before using it in an application.

Type two or more characters. Try “duplicate”, “webhook” or “retry”.