Utility functions & classes.
Yarn:
$ yarn add toosoon-utilsNPM:
$ npm install toosoon-utilsimport { lerp } from 'toosoon-utils/maths';
console.log(lerp(0.5, 0, 5)); // 2.5Check if a number is even.
value: Value to check.
isEven(value: number): boolean;Check if a number is odd.
value: Value to check.
isOdd(value: number): boolean;Check if a number is a power of 2.
value: Value to check.
isPowerOf2(value: number): boolean;Find closest power of 2 that fits a number.
value: Incoming value.[mode='ceil']: Can be'floor','ceil'or'round'.
toPowerOf2(value: number, mode?: string): number;Return the sign (positive or negative) of a number.
value: Value to check.
sign(value: number): number;Clamp a value between two bounds.
value: Value to clamp.[min=0]: Minimum boundary.[max=1]: Maximum boundary.
clamp(value: number, min?: number, max?: number): number;Round a number up to a nearest multiple.
value: Value to round.[multiple=1]: Multiple to round to.
snap(value: number, multiple?: number): number;Interpolate a value between two values using Linear interpolation (lerping).
t: Normalized time value to interpolate.min: Minimum value.max: Maximum value.
lerp(t: number, min: number, max: number): number;Normalize a value between two bounds.
value: Value to normalize.min: Minimum boundary.max: Maximum boundary.
normalize(value: number, min: number, max: number): number;Re-map a number from one range to another.
value: Value to re-map.currentMin: Lower bound of the value's current range.currentMax: Upper bound of the value's current range.targetMin: Lower bound of the value's target range.targetMax: Upper bound of the value's target range.
map(value: number, currentMin: number, currentMax: number, targetMin: number, targetMax: number): number;Interpolate a value between two values using Triangular interpolation.
t: Normalized time value to interpolate.min: Minimum value.max: Maximum value.peak: Peak value controling the interpolation triangle shape.
triLerp(t: number, min: number, max: number, peak: number): number;Interpolate a value using Exponential interpolation.
t: Normalized time value to interpolate.min: Minimum value.max: Maximum value.power: Exponent controling the interpolation curve shape.
expLerp(t: number, min: number, max: number, power: number): number;Interpolate a value using Quadratic Bézier interpolation.
t: Normalized time value to interpolate.p1: Start point.cp: Control point.p2: End point.
quadraticBezier(t: number, p1: number, cp: number, p2: number): number;Interpolate a value using Cubic Bézier interpolation.
t: Normalized time value to interpolate.p1: Start point.cp1: First control point.cp2: Second control point.p2: End point.
cubicBezier(t: number, p1: number, cp1: number, cp2: number, p2: number): number;Interpolate a value using Catmull-Rom interpolation.
t: Normalized time value to interpolate.p1: Start point.cp1: First control point.cp2: Second control point.p2: End point.
catmullRom(t: number, p1: number, cp1: number, cp2: number, p2: number): number;Modulo absolute a value based on a length.
value: Value to modulate.length: Total length.
modAbs(value: number, length: number): number;Move back and forth a value between 0 and length, so that it is never larger than length and never smaller than 0.
value: Value to modulate.length: Total length.
pingPong(value: number, length: number): number;Smooth a value using cubic Hermite interpolation.
value: Value to smooth.[min=0]: Minimum boundary.[max=1]: Maximum boundary.
smoothstep(value: number, min?: number, max?: number): number;Re-map the [0, 1] interval into [0, 1] parabola, such that corners are remaped to 0 and the center to 1.
x: Normalized coordinate on X axis.[power=1]: Parabola power.
parabola(x: number, power?: number): number;Return the sum of numbers.
array: Array of numbers.
sum(array: number[]): number;Return the average of numbers.
array: Array of numbers.
average(array: number[]): number;Smoothly interpolate a number toward another.
value: Value to interpolate.target: Destination of the interpolation.damping: A higher value will make the movement more sudden, and a lower value will make the movement more gradual.delta: Delta time (in seconds).
damp(value: number, target: number, damping: number, delta: number): number;Convert a radians value into degrees.
radians: Angle in radians.
toDegrees(radians: number): number;Convert a degrees value into radians.
degrees: Angle in degrees.
toRadians(degrees: number): number;Calculate the angle from a point to another.
x1: X-axis coordinate of the start point.y1: Y-axis coordinate of the start point.x2: X-axis coordinate of the end point.y2: Y-axis coordinate of the end point.
angle(x1: number, y1: number, x2: number, y2: number): number;Find the closest angle between to angles.
startAngle: Start angle (in radians).endAngle: End angle (in radians).
closestAngle(startAngle: number, endAngle: number): number;Calculate the distance between two points.
x1: X-axis coordinate of the start point.y1: Y-axis coordinate of the start point.x2: X-axis coordinate of the end point.y2: Y-axis coordinate of the end point.
distance(x1: number, y1: number, x2: number, y2: number): number;Calculate the length of the diagonal of a rectangle.
width: Width of the rectangle.height: Height of the rectangle.
diagonal(width: number, height: number): number;type FitInput = {
width: number;
height: number;
};
type FitOutput = {
left: number;
top: number;
width: number;
height: number;
scale: number;
};Make a target fit a container (cover mode).
target: Dimension of the target.container: Dimension of the container.
cover(target: FitInput, container: FitInput): FitOutput;Make a target fit a container (contain mode).
target: Dimension of the target.container: Dimension of the container.
contain(target: FitInput, container: FitInput): FitOutput;Normalize an hexadecimal string.
hex: Hexadecimal string.
normalizeHexString(hex: string): string;Convert RGB to hexadecimal.
rgb: RGB color.
rgbToHex([r, g, b]: [number, number, number]): number;Convert RGB to hexadecimal string.
rgb: RGB color.
rgbToHexString([r, g, b]: [number, number, number]): string;Convert hexadecimal to RGB.
hex: Hexadecimal color.
hexToRgb(hex: number | string): [number, number, number];Lighten a color.
hex: Hexadecimal color.[amount=0]: Amount of the color offset.
lighten(hex: string, amount?: number): string;Darken a color.
hex: Hexadecimal color.[amount=0]: Amount of the color offset.
darken(hex: string, amount?: number): string;Normalize an HSL string.
hsl: HSL string (format:'hsl(360, 100%, 100%)').
normalizeHslString(hsl: string): [number, number, number];Convert RGB to HSL.
rgb: RGB color.
rgbToHsl([r, g, b]: [number, number, number]): [number, number, number];Convert HSL to RGB.
hsl: HSL color.
hslToRgb([h, s, l]: [number, number, number]): [number, number, number];Convert RGB to HSB.
rgb: RGB color.
rgbToHsb([r, g, b]: [number, number, number]): [number, number, number];Convert HSB to RGB.
hsb: HSB color.
hsbToRgb([h, s, b]: [number, number, number]): [number, number, number];Convert LAB to HCL.
lab: LAB color.
labToHcl([l, a, b]: [number, number, number]): [number, number, number];Convert HCL to LAB.
hcl: HCL color.
hclToLab([h, c, l]: [number, number, number]): [number, number, number];Convert LAB to RGB.
lab: LAB color.
labToRgb([l, a, b]: [number, number, number]): [number, number, number];Convert RGB to LAB.
rgb: RGB color.
rgbToLab([r, g, b]: [number, number, number]): [number, number, number];Get the delta from two LAB colors.
labA: First LAB color.labB: Second LAB color.
deltaE(labA: [number, number, number], labB: [number, number, number]): number;Convert RGB to HCL.
rgb: RGB color.
rgbToHcl([r, g, b]: [number, number, number]): [number, number, number];Convert HCL to RGB.
hcl: HCL color.
hclToRgb([h, c, l]: [number, number, number]): [number, number, number];No-op function.
noop(): void;Promise wrapped setTimeout.
[delay=0]: Time to wait (in milliseconds).
wait(delay?: number): Promise<void>;Check if a value is defined.
value: Value to check.
isDefined(value: any): boolean;Create a debounced function that delays the execution of callback until a specified delay time has passed since the last call.
callback: Function to debounce.delay: Delay (in milliseconds).
debounce(callback: Function, delay: number): Function;Create a throttled function that limits the execution of callback to once every limit time.
callback: Function to throttle.limit: Minimum interval between two calls (in milliseconds).
throttle(callback: Function, limit: number): Function;Deferred promise implementation.
defer<T>(): Deferred<T>;Polyfill for now() functions.
now(): number;Capitalize a string.
string: String to capitalize.
capitalize(string: string): string;Convert a string to kebab-case: 'Hello world' -> 'hello-world'.
string: String to convert.
toKebabCase(string: string): string;Convert a string to snake_case: 'Hello world' -> 'hello_world'.
string: String to convert.
toSnakeCase(string: string): string;Convert a string to camelCase: 'Hello world' -> 'helloWorld'.
string: String to convert.
toCamelCase(string: string): string;Convert a string to PascalCase: 'Hello world' -> 'HelloWorld'.
string: String to convert.
toPascalCase(string: string): string;Convert a string to Train-Case: 'Hello world' -> 'Hello-World'.
string: String to convert.
toTrainCase(string: string): string;Convert a string to CONSTANT_CASE: 'Hello world' -> 'HELLO_WORLD'.
string: String to convert.
toConstantCase(string: string): string;Clean a path by removing its parameters.
path: Path to clean.
cleanPath(path: string): string;Convert a path by ensuring it has a trailing slash.
path: Path to convert.
addTrailingSlash(path: string): string;Convert a path by ensuring it has not a trailing slash.
path: Path to convert.
removeTrailingSlash(path: string): string;Get a query parameter.
property: Query property to check.
getQuery(property: string): string | null;Set a query parameter.
property: Query property to set.value: Value to set.
setQuery(property: string, value: string): void;Check if a query parameter exists.
property: Query property to check.
hasQuery(property: string): boolean;Find the closest parent that matches a selector.
element: Target element.selector: Selector or parent to match.
closest(element: Element | null, selector: Element | string): Element | null;Create a canvas and 2d context.
width: Width of the canvas.height: Height of the canvas.
createCanvas(width: number, height: number): { canvas: HTMLCanvasElement; ctx: CanvasRenderingContext2D };Inject CSS styles in document.head.
styles: CSS styles to inject.
injectStyles(styles: string): void;Download a Blob object into user files.
blob: Blob object to download.filename: Downloaded file name.
download(blob: Blob, filename: string): void;Upload a file from user files.
onLoad: Callback called once the file is loaded.[accept='']MIME type the file input should accept.
upload(onLoad: (dataUrl: string) => void, accept?: string): void;Generate a random boolean (true or false).
[probability=0.5]: Probability to get true.
randomBoolean(probability?: number): boolean;Generate a random sign (1 or -1).
[probability=0.5]: Probability to get 1.
randomSign(probability?: number): number;Generate a random floating-point number within a specified range.
[min=0]: Minimum boundary.[max=1]: Maximum boundary.[precision=2]: Number of digits after the decimal point.
randomFloat(min?: number, max?: number, precision?: number): number;Generate a random integer number within a specified range.
min: Minimum boundary.max: Maximum boundary.
randomInt(min: number, max: number): number;Generate a random hexadecimal color.
randomHexColor(): string;Pick a random item from a given array.
array: Array to pick the item from.
randomItem<T>(array: T[]): T | undefined;Pick a random property value from a given object.
object: Object to pick the property from.
randomObjectProperty<T>(object: Record<string, T>): T | undefined;Select a random index from an array of weighted items.
weights: Array of weights.
randomIndex(weights: number[]): number;Generate a random number fitting a Gaussian (normal) distribution.
[mean=0]: Central value.[spread=1]: Standard deviation.
randomGaussian(mean?: number, spread?: number): number;Produce a random 2D point around the perimiter of a unit circle.
[radius=1]: Radius of the circle.
onCircle(radius?: number): [number, number];Produce a random 2D point inside a unit circle.
[radius=1]: Radius of the circle.
insideCircle(radius?: number): [number, number];Produce a random 3D point on the surface of a sphere.
[radius=1]: Radius of the sphere.
onSphere(radius?: number): [number, number, number];Produce a random 3D point inside a sphere.
[radius=1]: Radius of the sphere.
insideSphere(radius?: number): [number, number, number];Credits: Seeding random number generator
Produce a 128-bit hash value from a string.
seed: Initial seed state.
cyrb128(prng: string | object): [number, number, number, number];Simple Fast Counter, Generator with a 128-bit state.
sfc32(a: number, b: number, c: number, d: number): number;SplitMix32, Generator with a 32-bit state.
splitmix32(a: number): number;Mulberry32, Generator with a 32-bit state.
mulberry32(a: number): number;Jenkins' Small Fast, Generator with a 32-bit state.
jsf32(a: number, b: number, c: number, d: number): number;xoshiro128**, Generator with a 128-bit state.
xoshiro128ss(a: number, b: number, c: number, d: number): number;Thanks to the above algorithms, a seed-based version of most of the random functions exist with additionnal parameters for a seed string and a PRNG algorithm function.
type PRNGParameters = string | { seed: string; algorithm: (...args: number[]) => number };Generate a pseudo-random number in the interval [0, 1]. It is the PRNG equivalent of Math.random().
prng: PRNG parameters.
random(prng: PRNGParameters): number;Generate a pseudo-random boolean (true or false).
prng: PRNG parameters.[probability=0.5]: Probability to get true.
randomBoolean(prng: PRNGParameters, probability?: number): boolean;Generate a pseudo-random sign (1 or -1).
prng: PRNG parameters.[probability=0.5]: Probability to get 1.
randomSign(prng: PRNGParameters, probability?: number): number;Generate a pseudo-random floating-point number within a specified range.
prng: PRNG parameters.[min=0]: Minimum boundary.[max=1]: Maximum boundary.[precision=2]: Number of digits after the decimal point.
randomFloat(prng: PRNGParameters, min?: number, max?: number, precision?: number): number;Generate a pseudo-random integer number within a specified range.
prng: PRNG parameters.min: Minimum boundary.max: Maximum boundary.
randomInt(prng: PRNGParameters, min: number, max: number): number;Generate a pseudo-random hexadecimal color.
prng: PRNG parameters.
randomHexColor(prng: PRNGParameters): string;Pick a pseudo-random item from a given array.
prng: PRNG parameters.array: Array to pick the item from.
randomItem<T>(prng: PRNGParameters, array: T[]): T | undefined;Pick a pseudo-random property value from a given object.
prng: PRNG parameters.object: Object to pick the property from.
randomObjectProperty<T>(prng: PRNGParameters, object: Record<string, T>): T | undefined;Select a pseudo-random index from an array of weighted items.
prng: PRNG parameters.weights: Array of weights.
randomIndex(prng: string | object, weights: number[]): number;Generate a pseudo-random number fitting a Gaussian (normal) distribution.
prng: PRNG parameters.[mean=0]: Central value.[spread=1]: Standard deviation.
randomGaussian(prng: string | object, mean?: number, spread?: number): number;See Geometry utility classes documentation here.
See Curves utility classes documentation here.
See Paths utility classes documentation here.
See Colors utility classes documentation here.
See FrameRate utility class documentation here.
EPSILON
PI
TWO_PI / TAU
HALF_PI
QUARTER_PI
W3CX11
MIT License, see LICENSE for details.
