Num
Numeric types and utilities with branded types for mathematical constraints.
Provides branded number types (Positive, Negative, Even, Odd, etc.) with runtime validation, mathematical operations, range types, and specialized numeric domains like Complex, Ratio, and BigInt. Includes type guards, ordering, and equivalence utilities.
Import
import { Num } from '@wollybeard/kit'
import * as Num from '@wollybeard/kit/num'
Namespaces
Degrees
Even
Finite
Float
InRange
Int
Natural
Negative
NonNegative
NonPositive
NonZero
Odd
Percentage
Positive
Radians
SafeInt
Whole
Zero
Prime
Ratio
Frac
Complex
BigInteger
Angle Conversion
[F]
degToRad
(degrees: Degrees): Radians
Parameters:
degrees
- The angle in degrees
Returns: The angle in radians
Convert degrees to radians. Most JavaScript math functions expect angles in radians, but humans often think in degrees. This converts from the familiar degree system (0-360) to radians (0-2π).
[F]
radToDeg
(radians: Radians): Degrees
Parameters:
radians
- The angle in radians
Returns: The angle in degrees
Convert radians to degrees. Math functions return angles in radians, but you might want to display them in degrees. This converts from radians (0-2π) to the familiar degree system (0-360).
Arithmetic
[F]
add
(a: number, b: number): number
Parameters:
a
- The first number to addb
- The second number to add
Returns: The sum of a and b
Add two numbers together.
[C]
addWith
;((a: number) => (b: number) => number)
Create a function that adds a specific number to any other number. This is useful when you want to add the same number multiple times.
[F]
subtract
(a: number, b: number): number
Parameters:
a
- The number to subtract from (minuend)b
- The number to subtract (subtrahend)
Returns: The difference between a and b
Subtract one number from another. Takes the second number away from the first number.
[C]
subtractWith
;((a: number) => (b: number) => number)
Create a function that subtracts other numbers from a specific number. This is useful when you have a starting value and want to subtract various amounts from it.
[F]
multiply
(a: number, b: number): number
Parameters:
a
- The first number (multiplicand)b
- The second number (multiplier)
Returns: The product of a and b
Multiply two numbers together. This gives you the result of adding a number to itself b times.
[C]
multiplyWith
;((b: number) => (a: number) => number)
Create a function that multiplies any number by a specific factor. This is useful for scaling values or converting units.
[F]
divide
(dividend: number, divisor: NonZero): number
Parameters:
dividend
- The number to be divided (what you're splitting up)divisor
- The non-zero number to divide by (how many parts to split into)
Returns: The quotient (result of division)
Divide one number by another. This splits the first number into equal parts based on the second number. The divisor must be non-zero.
[F]
divideWith
(divisor: NonZero): (dividend: number) => number
Parameters:
divisor
- The non-zero number to divide by
Returns: A function that divides its input by the divisor
Create a function that divides any number by a specific divisor. This is useful for splitting values into fixed portions.
Comparison
[F]
min
<A extends number, B extends number > (a: A, b: B): Min<A, B>
Parameters:
a
- The first number to compareb
- The second number to compare
Returns: The smaller of the two numbers
Find the smaller of two numbers. Returns whichever number is less.
[C]
minWith
;((a: number) => (b: number) => number)
Create a function that finds the minimum with a fixed first value. Useful for clamping or limiting values.
[F]
max
<A extends number, B extends number > (a: A, b: B): Max<A, B>
Parameters:
a
- The first number to compareb
- The second number to compare
Returns: The larger of the two numbers
Find the larger of two numbers. Returns whichever number is greater.
[C]
maxWith
;((a: number) => (b: number) => number)
Create a function that finds the maximum with a fixed first value. Useful for ensuring minimum values.
Constants
[C]
PI
number
The mathematical constant pi (π). Pi is the ratio of a circle's circumference to its diameter. Approximately 3.14159...
[C]
E
number
The mathematical constant e (Euler's number). The base of natural logarithms, approximately 2.71828... It appears naturally in exponential growth and compound interest.
[C]
TAU
number
The mathematical constant tau (τ). Tau is 2π, representing a full circle in radians. Some mathematicians prefer tau over pi for circular calculations. Approximately 6.28318...
[C]
GOLDEN_RATIO
number
The golden ratio (φ, phi). A special number appearing in nature, art, and architecture. When a line is divided so that the whole length divided by the long part equals the long part divided by the short part. Approximately 1.61803...
Exponentiation
[F]
power
(base: number, exponent: number): number
Parameters:
base
- The number to be multiplied by itselfexponent
- How many times to multiply the base by itself
Returns: The result of base raised to the exponent power
Raise a number to a power (exponentiation). This multiplies the base number by itself 'exponent' times. For best results, use finite numbers to avoid NaN/Infinity.
[C]
powerWith
;((exponent: number) => (base: number) => number)
Create a function that raises any number to a specific power. This is useful for repeated exponentiations.
Interpolation
[F]
lerp
(start: number, end: number, t: number): number
Parameters:
start
- The starting value (when t = 0)end
- The ending value (when t = 1)t
- The interpolation factor (typically between 0 and 1)
Returns: The interpolated value
Linear interpolation between two values. Calculates a value between start and end based on the interpolation factor t.
[F]
lerpBetween
(start: number, end: number): (t: number) => number
Parameters:
start
- The starting valueend
- The ending value
Returns: A function that takes t and returns the interpolated value
Create a function that linearly interpolates between two fixed values. Useful for creating reusable interpolation functions.
Iteration
[F]
times
<T>(n: number, fn: (index: number) => T): T[]
Parameters:
n
- The number of times to execute the functionfn
- The function to execute, receives the current index
Returns: An array of the function results
Execute a function n times and collect the results. The function receives the current index (0-based) as its argument.
[F]
timesWith
<T>(fn: (index: number) => T): (n: number) => T[]
Parameters:
fn
- The function to execute
Returns: A function that takes n and returns the results array
Create a function that executes another function n times. Useful for partial application of the times function.
Logarithms
[F]
log
(value: Positive): number
Parameters:
value
- The positive number to find the natural logarithm of
Returns: The natural logarithm of the value
Calculate the natural logarithm (base e) of a number. The logarithm tells you what power you need to raise e (≈2.718) to get your number. It's the inverse operation of exponential (e^x).
[F]
log10
(value: Positive): number
Parameters:
value
- The positive number to find the base-10 logarithm of
Returns: The base-10 logarithm of the value
Calculate the base-10 logarithm of a number. This tells you what power you need to raise 10 to get your number. It's commonly used for measuring orders of magnitude.
[F]
log2
(value: Positive): number
Parameters:
value
- The positive number to find the base-2 logarithm of
Returns: The base-2 logarithm of the value
Calculate the base-2 logarithm of a number. This tells you what power you need to raise 2 to get your number. It's commonly used in computer science for binary operations.
Number Theory
[F]
gcd
(a: Int, b: Int): Natural
Parameters:
a
- The first integerb
- The second integer
Returns: The greatest common divisor as a positive integer
Find the greatest common divisor (GCD) of two integers. The GCD is the largest positive integer that divides both numbers evenly. Also known as the greatest common factor (GCF).
[C]
gcdWith
;((a: Int) => (b: Int) => Natural)
Create a function that finds the GCD with a fixed first value. Useful for finding common factors with a specific number.
[F]
lcm
(a: Int, b: Int): Whole
Parameters:
a
- The first integerb
- The second integer
Returns: The least common multiple as a non-negative integer
Find the least common multiple (LCM) of two integers. The LCM is the smallest positive integer that is divisible by both numbers. Returns 0 if either input is 0.
[C]
lcmWith
;((a: Int) => (b: Int) => Whole)
Create a function that finds the LCM with a fixed first value. Useful for finding common multiples with a specific number.
Range Generation
[F]
range
(start: number, end: number, options?: RangeOptions | undefined): number[]
Parameters:
start
- The starting value (inclusive)end
- The ending value (exclusive by default)options
- Configuration options
Returns: An array of numbers in the range
Generate an array of numbers in a range. By default, the range is exclusive of the end value and uses a step of 1.
[F]
rangeFrom
(start: number): (end: number, options?: RangeOptions | undefined) => number[]
Parameters:
start
- The starting value
Returns: A function that takes end and options and returns the range
Create a function that generates a range from a specific start value. Useful for creating ranges with a fixed starting point.
[F]
rangeTo
(end: number): (start: number, options?: RangeOptions | undefined) => number[]
Parameters:
end
- The ending value
Returns: A function that takes start and options and returns the range
Create a function that generates a range to a specific end value. Useful for creating ranges with a fixed ending point.
[F]
rangeStep
(start: number, end: number, step: number): number[]
Parameters:
start
- The starting valueend
- The ending valuestep
- The step between values
Returns: An array of numbers in the range
Generate a range with a specific step. A convenience function that makes the step explicit.
[F]
rangeStepWith
(step: number): (start: number, end: number) => number[]
Parameters:
step
- The step between values
Returns: A function that takes start and end and returns the range
Create a function that generates ranges with a specific step. Useful for creating consistent stepped ranges.
[F]
rangeInclusive
(start: number, end: number): number[]
Parameters:
start
- The starting valueend
- The ending value (inclusive)
Returns: An array of numbers from start to end (inclusive)
Create an inclusive range. A convenience function that always includes the end value.
[F]
sequence
(n: number): number[]
Parameters:
n
- The number of integers to generate
Returns: An array of integers from 0 to n-1
Generate a sequence of integers starting from 0. A convenience function equivalent to range(0, n).
Range Mapping
[F]
mapRange
(value: number, fromMin: number, fromMax: number, toMin: number, toMax: number): number
Parameters:
value
- The value to mapfromMin
- The minimum of the source rangefromMax
- The maximum of the source rangetoMin
- The minimum of the target rangetoMax
- The maximum of the target range
Returns: The mapped value in the target range
Map a value from one range to another. Converts a value from the source range [fromMin, fromMax] to the target range [toMin, toMax].
[F]
mapRangeFrom
(fromMin: number, fromMax: number, toMin: number, toMax: number): (value: number) => number
Parameters:
fromMin
- The minimum of the source rangefromMax
- The maximum of the source rangetoMin
- The minimum of the target rangetoMax
- The maximum of the target range
Returns: A function that takes a value and returns the mapped value
Create a function that maps values from one range to another. Useful for creating reusable range mapping functions.
Range Operations
[F]
wrap
(value: number, min: number, max: number): number
Parameters:
value
- The value to wrapmin
- The minimum of the rangemax
- The maximum of the range
Returns: The wrapped value within [min, max)
Constrain a value to be within a range, wrapping around if necessary. Unlike clamp which stops at boundaries, wrap continues from the other side.
[F]
wrapWithin
(min: number, max: number): (value: number) => number
Parameters:
min
- The minimum of the rangemax
- The maximum of the range
Returns: A function that takes a value and returns the wrapped value
Create a function that wraps values within a specific range.
Roots
[F]
sqrt
<T extends NonNegative>(value: T): Sqrt<T>
Parameters:
value
- The non-negative number to find the square root of
Returns: The square root of the value
Calculate the square root of a non-negative number. The square root is a number that, when multiplied by itself, gives the original number. For type safety, this requires a non-negative input to avoid NaN results.
[F]
cbrt
(value: number): number
Parameters:
value
- The number to find the cube root of
Returns: The cube root of the value
Calculate the cube root of a number. The cube root is a number that, when multiplied by itself three times, gives the original number.
Rounding
[F]
round
(value: number, precision?: number = 0): number
Parameters:
value
- The number to roundprecision
- Number of decimal places to keep (default: 0 for whole numbers)
Returns: The rounded number
Round a number to the nearest integer or to a specific number of decimal places. Rounding follows standard rules: 0.5 and above rounds up, below 0.5 rounds down.
[C]
roundWith
;((precision?: number | undefined) => (value: number) => number)
Create a function that rounds numbers to a specific number of decimal places. This is useful when you need consistent precision across multiple values.
[F]
floor
<T extends Finite>(value: T): Int
Parameters:
value
- The finite number to round down
Returns: The largest integer less than or equal to the value
Round a number down to the nearest integer. This always rounds towards negative infinity, removing any decimal part. The input must be finite to ensure a valid integer result.
[F]
ceil
<T extends Finite>(value: T): Int
Parameters:
value
- The finite number to round up
Returns: The smallest integer greater than or equal to the value
Round a number up to the nearest integer. This always rounds towards positive infinity. The input must be finite to ensure a valid integer result.
[F]
trunc
<T extends Finite>(value: T): Int
Parameters:
value
- The finite number to truncate
Returns: The integer part of the number
Remove the decimal part of a number (truncate). This simply cuts off the decimal portion, always rounding towards zero. The input must be finite to ensure a valid integer result.
Trigonometry
[F]
sin
<T extends Finite>(radians: T): Sin<_T>
Parameters:
radians
- The angle in radians (must be finite)
Returns: The sine of the angle, always between -1 and 1
Calculate the sine of an angle. Sine is a trigonometric function that represents the ratio of the opposite side to the hypotenuse in a right triangle. The angle must be in radians and finite.
[F]
cos
<T extends Finite>(radians: T): Cos<_T>
Parameters:
radians
- The angle in radians (must be finite)
Returns: The cosine of the angle, always between -1 and 1
Calculate the cosine of an angle. Cosine is a trigonometric function that represents the ratio of the adjacent side to the hypotenuse in a right triangle. The angle must be in radians and finite.
[F]
tan
(radians: Finite): number
Parameters:
radians
- The angle in radians (must be finite)
Returns: The tangent of the angle
Calculate the tangent of an angle. Tangent is the ratio of sine to cosine, or the ratio of the opposite side to the adjacent side in a right triangle. The angle must be in radians and finite.
[F]
asin
(value: InRange<-1, 1>): Radians
Parameters:
value
- A number between -1 and 1 (inclusive)
Returns: The angle in radians, between -PI/2 and PI/2
Calculate the arcsine (inverse sine) of a value. This gives you the angle whose sine is the input value. The input must be in the range [-1, 1] to get a valid result. The result is in radians.
[F]
acos
(value: InRange<-1, 1>): Radians
Parameters:
value
- A number between -1 and 1 (inclusive)
Returns: The angle in radians, between 0 and PI
Calculate the arccosine (inverse cosine) of a value. This gives you the angle whose cosine is the input value. The input must be in the range [-1, 1] to get a valid result. The result is in radians.
[F]
atan
(value: Finite): Radians
Parameters:
value
- Any finite number (the tangent of the angle)
Returns: The angle in radians, between -PI/2 and PI/2
Calculate the arctangent (inverse tangent) of a value. This gives you the angle whose tangent is the input value. The input must be finite to get a meaningful angle. The result is in radians.
[F]
atan2
(y: Finite, x: Finite): Radians
Parameters:
y
- The y-coordinate of the point (must be finite)x
- The x-coordinate of the point (must be finite)
Returns: The angle in radians, between -PI and PI
Calculate the angle from the positive x-axis to a point (x, y). This is like atan(y/x) but handles all quadrants correctly and avoids division by zero. Both coordinates must be finite to get a meaningful angle. The result is in radians.
[C]
atan2With
;((y: Finite) => (x: Finite) => Radians)
Create a function that calculates atan2 with a fixed y value. Useful for repeated calculations with the same y offset.
Other
[T]
BigInt
type BigInt = BigInteger_
[C]
Arb
Arb<number>
[C]
Eq
Eq<number>
Eq trait implementation for numbers.
Provides number equality comparison using strict equality (===). Handles special cases like NaN, which is never equal to itself.
Examples:
import { Num } from '@wollybeard/kit'
Num.Eq.is(42, 42) // true
Num.Eq.is(3.14, 3.14) // true
Num.Eq.is(0, -0) // true (positive and negative zero are equal)
Num.Eq.is(NaN, NaN) // false (NaN is never equal to itself)
[C]
Type
Type<number>
Type trait implementation for numbers.
Provides type checking for number values using typeof.
Examples:
import { Num } from '@wollybeard/kit'
Num.Type.is(42) // true
Num.Type.is(3.14) // true
Num.Type.is(NaN) // true (NaN is a number)
Num.Type.is('42') // false
[T]
Floor
type Floor<_T extends number> = Int
Type-level floor transformation. Floor always returns an integer.
[T]
Ceil
type Ceil<_T extends number> = Int
Type-level ceil transformation. Ceil always returns an integer.
[T]
Trunc
type Trunc<_T extends number> = Int
Type-level trunc transformation. Trunc always returns an integer.
[T]
Sqrt
type Sqrt<T extends number> = T extends Positive ? Positive
: T extends NonNegative ? NonNegative
: number
Type-level sqrt transformation. Square root of non-negative returns non-negative. Square root of positive returns positive (except for 0).
[T]
Sin
type Sin<_T extends number> = InRange<-1, 1>
Type-level sine transformation. Sine always returns a value in the range [-1, 1].
[T]
Cos
type Cos<_T extends number> = InRange<-1, 1>
Type-level cosine transformation. Cosine always returns a value in the range [-1, 1].
[U]
Min
type Min<A extends number, B extends number> = A | B
Type-level min transformation. Returns the union of both input types (the more general type).
[U]
Max
type Max<A extends number, B extends number> = A | B
Type-level max transformation. Returns the union of both input types (the more general type).
[F]
is
(value: unknown): boolean
Type predicate to check if value is a number. Excludes NaN by default.
[F]
isNaN
(value: unknown): boolean
Type predicate to check if value is NaN.
[T]
Abs
type Abs<T extends number> = T extends Positive ? Positive
: T extends Negative ? Positive
: T extends NonPositive ? NonNegative
: T extends Zero ? Zero
: NonNegative
Type-level absolute value transformation. Maps number types to their absolute value types.
[F]
abs
<T extends number>(value: T): Abs<T>
Parameters:
value
- The number to get absolute value of
Returns: The absolute value with appropriate branded type
Get absolute value. Returns the non-negative magnitude of a number.
[T]
Sign
type Sign<T extends number> = T extends Positive ? 1
: T extends Negative ? -1
: T extends Zero ? 0
: -1 | 0 | 1
Type-level sign transformation. Maps number types to their sign (-1, 0, 1).
[F]
sign
<T extends number>(value: T): Sign<T>
Parameters:
value
- The number to get the sign of
Returns: -1, 0, or 1 with precise type
Get sign of number (-1, 0, 1). Returns -1 for negative numbers, 0 for zero, and 1 for positive numbers.
[F]
inc
(value: number): number
Increment by 1.
[F]
dec
(value: number): number
Decrement by 1.
[T]
Mod
type Mod<_T extends number, _U extends NonZero> = NonNegative
Type-level modulo transformation. Modulo always returns a non-negative result.
[F]
mod
<T extends number, U extends NonZero > (dividend: T, divisor: U): NonNegative
Parameters:
dividend
- The number to dividedivisor
- The non-zero number to divide by
Returns: The positive remainder
Modulo operation that always returns positive result. Unlike the % operator, this always returns a non-negative result. The divisor must be non-zero for a valid result.
[F]
modOn
<T extends number>(dividend: T): <U extends NonZero>(divisor: U) => NonNegative
Parameters:
dividend
- The fixed dividend
Returns: A function that takes a divisor and returns the modulo
Create a function that calculates modulo with a fixed dividend.
[F]
modWith
<U extends NonZero>(divisor: U): <T extends number>(dividend: T) => NonNegative
Parameters:
divisor
- The fixed non-zero divisor
Returns: A function that takes a dividend and returns the modulo
Create a function that calculates modulo with a fixed divisor. Useful for wrapping values in a fixed range.
[T]
NumberLiteral
type NumberLiteral = number
Number literal type.
[T]
PlusOne
type PlusOne<$n extends NumberLiteral> = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
][
$n
]
Add one to a number literal type.
[T]
MinusOne
type MinusOne<$n extends NumberLiteral> = [
-1,
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
][
$n
]
Subtract one from a number literal type.
[I]
RangeOptions
interface RangeOptions {
/**
* The step between each number in the range.
* @default 1
*/
step?: number
/**
* Whether to include the end value in the range.
* @default false
*/
inclusive?: boolean
}
Options for generating numeric ranges.