diff --git a/src/math.test.ts b/src/math.test.ts index bd3446f..65881de 100644 --- a/src/math.test.ts +++ b/src/math.test.ts @@ -1,5 +1,5 @@ import { expect, it } from 'vitest' -import { sum } from './math' +import { lerp, remap, sum } from './math' it('sum', () => { expect(sum(1, 2, 3)).toEqual(6) @@ -9,3 +9,27 @@ it('sum', () => { // @ts-expect-error expect(sum(1, 2, [1, 2, 3])).toEqual(9) }) + +it('lerp', () => { + expect(lerp(0, 2, 0)).toEqual(0) + expect(lerp(0, 2, 1)).toEqual(2) + expect(lerp(0, 2, 0.5)).toEqual(1) + + expect(lerp(-10, 10, 0.5)).toEqual(0) + expect(lerp(10, -10, 0.5)).toEqual(0) + + expect(lerp(0, 1, -1.5)).toEqual(0) + expect(lerp(0, 1, 2.5)).toEqual(1) +}) + +it('remap', () => { + expect(remap(0, 0, 1, 0, 10)).toEqual(0) + expect(remap(1, 0, 1, 0, 10)).toEqual(10) + expect(remap(0.5, 0, 1, 0, 10)).toEqual(5) + + expect(remap(0.5, -1, 1, 0, 1)).toEqual(0.75) + expect(remap(0.25, 0, 1, -1, 1)).toEqual(-0.5) + + expect(remap(2, 0, 1, 5, 10)).toEqual(10) + expect(remap(-1, 0, 1, 5, 10)).toEqual(5) +}) diff --git a/src/math.ts b/src/math.ts index 474a3a5..8d96596 100644 --- a/src/math.ts +++ b/src/math.ts @@ -7,3 +7,32 @@ export function clamp(n: number, min: number, max: number) { export function sum(...args: number[] | number[][]) { return flattenArrayable(args).reduce((a, b) => a + b, 0) } + +/** + * Linearly interpolates between `min` and `max` based on `t` + * + * @category Math + * @param t The interpolation value clamped between 0 and 1 + * @example + * ``` + * const value = lerp(0, 2, 0.5) // value will be 1 + * ``` + */ +export function lerp(min: number, max: number, t: number) { + const interpolation = clamp(t, 0.0, 1.0) + return min + (max - min) * interpolation +} + +/** + * Linearly remaps a clamped value from its source range [`inMin`, `inMax`] to the destination range [`outMin`, `outMax`] + * + * @category Math + * @example + * ``` + * const value = remap(0.5, 0, 1, 200, 400) // value will be 300 + * ``` + */ +export function remap(n: number, inMin: number, inMax: number, outMin: number, outMax: number) { + const interpolation = (n - inMin) / (inMax - inMin) + return lerp(outMin, outMax, interpolation) +}