Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/Math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,27 @@ export const bin = (value: boolean): 0 | 1 => {
return value ? 1 : 0;
};

/**
* @summary generate a step function by comparing two values
* @worklet
*/
export const step = (value: number, edge: number) => {
"worklet";
return value < edge ? 0 : 1;
};

/**
* @summary Perform Hermite interpolation between two values
* @worklet
*/
export const smoothstep = (value: number, edge0: number, edge1: number) => {
"worklet";
// Scale, bias and saturate x to 0..1 range
const x = clamp((value - edge0) / (edge1 - edge0), 0, 1);
// Evaluate polynomial
return x * x * (3 - 2 * x);
};

/**
* Linear interpolation
* @param value
Expand Down Expand Up @@ -218,3 +239,21 @@ export const cubicBezierYForX = (
.filter((root) => root >= 0 && root <= 1)[0];
return cubicBezier(t, a.y, b.y, c.y, d.y);
};

/**
* @summary Euclidean distance between two vectors
* @worklet
*/
export const dist = (v1: Vector, v2: Vector) => {
"worklet";
return Math.sqrt((v1.x - v2.x) ** 2 + (v1.y - v2.y) ** 2);
};

/**
* @summary Returns true if a approximates b. Default precision is 0.001
* @worklet
*/
export const approximates = (a: number, b: number, precision = 0.001) => {
"worklet";
return Math.abs(a - b) <= precision;
};
27 changes: 27 additions & 0 deletions src/__tests__/Math.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import {
toRad,
toDeg,
cubicBezierYForX,
dist,
approximates,
step,
smoothstep,
} from "../Math";
import { vec } from "../Vectors";

Expand Down Expand Up @@ -74,3 +78,26 @@ test("cubicBezierYForX2()", () => {
const d = vec.create(227, 89);
expect(Math.round(cubicBezierYForX(x, a, b, c, d))).toBe(y);
});

test("dist()", () => {
const v1 = { x: 0, y: 0 };
const v2 = { x: 100, y: 100 };
expect(dist(v1, v2)).toBe(Math.sqrt(100 ** 2 + 100 ** 2));
});

test("approximates()", () => {
expect(approximates(1, 1)).toBe(true);
expect(approximates(1, 1.001)).toBe(true);
expect(approximates(1, 1.0011)).toBe(false);
expect(approximates(1, 2, 1)).toBe(true);
});

test("step()", () => {
expect(step(1.5, 1)).toBe(1);
expect(step(0.5, 1)).toBe(0);
});

test("smoothstep()", () => {
expect(smoothstep(1.5, 1, 2)).toBe(0.5);
expect(smoothstep(0.5, 1, 2)).toBe(0);
});