Math related functions
yarn add @typed/math
# or
npm install --save @typed/math
All functions are curried!
Add 2 numbers together
See the code
export const add = curry2(__add)
function __add(x: number, y: number): number {
return x + y
}
Subtracts 1
from a number.
See the code
export const decrement = add(-1)
Divides 2 numbers
See the code
export const divide = curry2(__divide)
function __divide(right: number, left: number): number {
return left / right
}
Adds 1 to a number.
See the code
export const increment = add(1)
Calculates the average of a list of numbers.
See the code
export const mean = (numbers: List<number>) => divide(numbers.length, sum(numbers))
Calculates the median of a List
. If the calculated median is NaN
a Nothing
is returned otherwise a Just
containing the median will be returned.
See the code
export function median(numbers: List<number>): Maybe<number> {
const length = numbers.length
if (length === 0) return Nothing
const width = 2 - (length % 2)
const index = (length - width) / 2
const medianNumbers = slice(index, Maybe.of(index + width), sort<number>(ascend(x => x), numbers))
return numberToMaybe(mean(medianNumbers))
}
function numberToMaybe(num: number): Maybe<number> {
return Number.isNaN(num) ? Nothing : Maybe.of(num)
}
Applies %
to 2 numbers.
See the code
export const modulo = curry2(__modulo)
function __modulo(right: number, left: number): number {
return left % right
}
Multiplies 2 numbers.
See the code
export const multiply = curry2(__multiply)
function __multiply(x: number, y: number): number {
return x * y
}
Negates a number.
See the code
export const negate = (n: number): number => -n
Applies a base to the exponent power.
See the code
export const pow: Pow = curry2(__pow)
export type Pow = {
(exponent: number, base: number): number
(exponent: number): (base: number) => number
}
function __pow(exponent: number, base: number): number {
return Math.pow(base, exponent)
}
Calculates the produce of a list of numbers.
See the code
export const product: (numbers: List<number>) => number = reduce(multiply, 1)
Subtracts one number from another.
See the code
export const subtract = curry2(__subtract)
function __subtract(right: number, left: number): number {
return left - right
}
Adds together all of the numbers in a list.
See the code
export const sum: (numbers: List<number>) => number = reduce(add, 0)