Skip to content

Commit f8b244d

Browse files
authored
feat(math): lerp and remap utils (#31)
1 parent fb02b90 commit f8b244d

2 files changed

Lines changed: 54 additions & 1 deletion

File tree

‎src/math.test.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import{expect,it}from'vitest'
2-
import{sum}from'./math'
2+
import{lerp,remap,sum}from'./math'
33

44
it('sum',()=>{
55
expect(sum(1,2,3)).toEqual(6)
@@ -9,3 +9,27 @@ it('sum', () => {
99
// @ts-expect-error
1010
expect(sum(1,2,[1,2,3])).toEqual(9)
1111
})
12+
13+
it('lerp',()=>{
14+
expect(lerp(0,2,0)).toEqual(0)
15+
expect(lerp(0,2,1)).toEqual(2)
16+
expect(lerp(0,2,0.5)).toEqual(1)
17+
18+
expect(lerp(-10,10,0.5)).toEqual(0)
19+
expect(lerp(10,-10,0.5)).toEqual(0)
20+
21+
expect(lerp(0,1,-1.5)).toEqual(0)
22+
expect(lerp(0,1,2.5)).toEqual(1)
23+
})
24+
25+
it('remap',()=>{
26+
expect(remap(0,0,1,0,10)).toEqual(0)
27+
expect(remap(1,0,1,0,10)).toEqual(10)
28+
expect(remap(0.5,0,1,0,10)).toEqual(5)
29+
30+
expect(remap(0.5,-1,1,0,1)).toEqual(0.75)
31+
expect(remap(0.25,0,1,-1,1)).toEqual(-0.5)
32+
33+
expect(remap(2,0,1,5,10)).toEqual(10)
34+
expect(remap(-1,0,1,5,10)).toEqual(5)
35+
})

‎src/math.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,32 @@ export function clamp(n: number, min: number, max: number) {
77
exportfunctionsum(...args: number[]|number[][]){
88
returnflattenArrayable(args).reduce((a,b)=>a+b,0)
99
}
10+
11+
/**
12+
* Linearly interpolates between `min` and `max` based on `t`
13+
*
14+
* @category Math
15+
* @param t The interpolation value clamped between 0 and 1
16+
* @example
17+
* ```
18+
* const value = lerp(0, 2, 0.5) // value will be 1
19+
* ```
20+
*/
21+
exportfunctionlerp(min: number,max: number,t: number){
22+
constinterpolation=clamp(t,0.0,1.0)
23+
returnmin+(max-min)*interpolation
24+
}
25+
26+
/**
27+
* Linearly remaps a clamped value from its source range [`inMin`, `inMax`] to the destination range [`outMin`, `outMax`]
28+
*
29+
* @category Math
30+
* @example
31+
* ```
32+
* const value = remap(0.5, 0, 1, 200, 400) // value will be 300
33+
* ```
34+
*/
35+
exportfunctionremap(n: number,inMin: number,inMax: number,outMin: number,outMax: number){
36+
constinterpolation=(n-inMin)/(inMax-inMin)
37+
returnlerp(outMin,outMax,interpolation)
38+
}

0 commit comments

Comments
 (0)