Skip to content

Common math utilities #6803

@lionel-rowe

Description

@lionel-rowe

Is your feature request related to a problem? Please describe.

Common math utilities you've probably written 100 times, like modulo, clamp, roundTo, sum:

// https://github.com/tc39/proposal-integer-and-modulus-math
export function modulo(n: number, m: number) {
	return ((n % m) + m) % m
}

// https://github.com/tc39/proposal-math-clamp
export function clamp(n: number, min: number, max: number) {
	return Math.min(Math.max(n, min), max)
}

// basically `Number#toFixed` but returning a number instead of a string
type Strategy = 'round' | 'floor' | 'ceil' | 'trunc' 
export function roundTo(n: number, digits: number, strategy: Strategy = 'round') {
	const factor = 10 ** digits
	return Math[strategy](n * factor) / factor
}

// https://github.com/tc39/proposal-math-sum
// (naive implementation, just for example)
// (the proposal version, which is more strictly correct, is stage 3 with two implementations, so probably not worth adding this one)
export function sum(...values: number[]) {
	return values.reduce((a, b) => a + b, 0)
}

Describe the solution you'd like

A dedicated math package containing these utilities and probably others.

Describe alternatives you've considered

N/A

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions