Skip to content

Commit

Permalink
feat(math): lerp and remap utils (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
osalinasv committed May 31, 2023
1 parent fb02b90 commit f8b244d
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/math.test.ts
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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)
})
29 changes: 29 additions & 0 deletions src/math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit f8b244d

Please sign in to comment.