Utility functions & classes.
Yarn:
$ yarn add toosoon-utils
NPM:
$ npm install toosoon-utils
import { lerp } from 'toosoon-utils/maths';
console.log(lerp(0.5, 0, 5)); // 2.5
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];
Find the closest parent that matches a selector.
-
element
: Target element. -
selector
: Selector or parent to match.
closest(element: Element, 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;
No-op function.
noop(): void;
Promise wrapped setTimeout.
-
[timeout=0]
: Time to wait (in milliseconds).
wait(timeout?: number): Promise<void>;
Deferred promise implementation.
defer<T>(): Deferred<T>;
Polyfill for now()
functions.
now(): 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 value of the first point. -
y1
: Y value of the first point. -
x2
: X value of the second point. -
y2
: Y value of the second point.
angle(x1: number, y1: number, x2: number, y2: number): number;
Find the closest angle between to angles.
-
source
: Source angle in radians. -
target
: Target angle in radians.
closestAngle(source: number, target: number): number;
Calculate the distance between two points.
-
x1
: X coord of the first point. -
y1
: Y coord of the first point. -
x2
: X coord of the second point. -
y2
: Y coord of the second 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;
Convert radians to a 3D point on the surface of a unit sphere.
-
radius
: Radius of the sphere -
phi
: Polar angle from the y (up) axis [0, PI] -
theta
: Equator angle around the y (up) axis [0, 2*PI] -
[target]
: Target vector
radToSphere(radius: number, phi: number, theta: number, target?: Vector3): Vector3;
Make a target fit a container (cover mode).
-
target
: Dimension of the target. -
container
: Dimension of the container.
cover(target: object, container: object): object;
Make a target fit a container (contain mode).
-
target
: Dimension of the target. -
container
: Dimension of the container.
contain(target: object, container: object): object;
Check 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;
Linear interpolation between two values (lerping).
-
value
: Normalized value to interpolate. -
min
: Minimum value. -
max
: Maximum value.
lerp(value: number, min: number, max: number): number;
Triangular interpolation between two values.
-
value
: Normalized value to interpolate. -
min
: Minimum value. -
max
: Maximum value. -
target
: Triangle target value.
triLerp(value: number, min: number, max: number, target: number): number;
Exponential interpolation between two values.
-
value
: Value to interpolate. -
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.
expLerp(value: number, currentMin: number, currentMax: number, targetMin: number, targetMax: 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;
Round a number up to a nearest multiple.
-
value
: Value to round. -
[multiple=1]
: Multiple to round to.
roundTo(value: number, multiple?: 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;
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 are exist with additionnal parameters for a seed
string and a PRNG algorithm
function.
PRNG parameters:
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 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;
Produce a random 2D point around the perimiter of a unit circle.
-
[radius=1]
: Radius of the circle. -
[target]
: Target vector.
onCircle(radius?: number, target?: Vector2): Vector2;
Produce a random 2D point inside a unit circle.
-
[radius=1]
: Radius of the circle. -
[target]
Target vector.
insideCircle(radius?: number, target?: Vector2): Vector2;
Produce a random 3D point on the surface of a unit sphere.
-
[radius=1]
: Radius of the sphere. -
[target]
: Target vector.
onSphere(radius?: number, target?: Vector3): Vector3;
Produce a random 3D point inside a unit sphere.
-
[radius=1]
: Radius of the sphere. -
[target]
: Target vector.
insideSphere(radius?: number, target?: Vector3): Vector3;
Capitalize a string.
-
string
: String to capitalize.
capitalize(string: string): string;
Clean a path by removing params.
-
path
: Path to clean.
cleanPath(path: string): string;
Utility class for generating color scales and interpolating between colors.
-
new ColorScale(input, target)
-
.colors:
Array<[number, number, number]>
-
static
.generate(input, target, length):Array<[number, number, number]>
-
static
.interpolate(inputColor, targetColor, value):[number, number, number]
-
.colors:
Parameter | Type | Default | Description |
---|---|---|---|
input | ColorRepresentation |
Input color representation. | |
target | ColorRepresentation |
Target color representation. | |
length | number |
5 |
Amount of colors composing the color scale. |
settings | ColorScaleSettings |
{ colorSpace: 'rgb' } |
Color scale generation settings. |
[settings.colorSpace] | 'rgb' | 'hsl' | 'hsb' | 'hcl' |
'rgb' |
Color scale color space. |
HCL color scales come with a bunch of other settings, so when settings.colorSpace
is equal to 'hcl'
, the following settings are parameterable:
Parameter | Type | Default | Description |
---|---|---|---|
[settings.mode] | 'qualitative' | 'sequential' | 'diverging' |
Color scale mode. | |
[settings.triangular] | number |
Triangular interpolation target value. |
|
[settings.powerStrength] | number |
1 |
Interpolation power strength value. |
[settings.hueOffset] | number |
0 |
Target color hue offset. |
[settings.chromaOffset] | number |
0 |
Target color chroma offset. |
[settings.luminanceOffset] | number |
0 |
Target color luminance offset. |
Learn more about HCL-Based Color Palettes.
Array of colors composing the color scale.
ColorScale.colors: Array<[number, number, number]>;
Static method for generating a color scale.
-
input
: Input color representation. -
target
: Target color representation. -
length
: Amount of colors composing the color scale. -
[settings]
: Color scale generation settings.
static ColorScale.generate(
input: ColorRepresentation,
target: ColorRepresentation,
length: number,
settings?: ColorScaleSettings
): Array<[number, number, number]>;
Static method for interpolating between colors.
-
inputColor
: Input color. -
targetColor
: Target color. -
value
: Interpolation normalized value. -
[settings]
: Color scale settings.
static ColorScale.interpolate(
inputColor: [number, number, number],
targetColor: [number, number, number],
value: number,
settings?: ColorScaleSettings
): [number, number, number];
Utility class for controlling FPS calls.
Parameter | Type | Default | Description |
---|---|---|---|
fps | number |
30 |
Frame per second limit. |
Frame per second limit.
FrameRate.fps: number;
Return true if elapsed time since last update is higher than current FPS.
FrameRate.update(): boolean;
EPSILON
PI
TWO_PI
HALF_PI
QUARTER_PI
W3CX11
MIT License, see LICENSE for details.