There was an error while loading. Please reload this page.
lerp
remap
1 parent fb02b90 commit f8b244dCopy full SHA for f8b244d
2 files changed
src/math.test.ts
@@ -1,5 +1,5 @@
1
import{expect,it}from'vitest'
2
-import{sum}from'./math'
+import{lerp,remap,sum}from'./math'
3
4
it('sum',()=>{
5
expect(sum(1,2,3)).toEqual(6)
@@ -9,3 +9,27 @@ it('sum', () => {
9
// @ts-expect-error
10
expect(sum(1,2,[1,2,3])).toEqual(9)
11
})
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
@@ -7,3 +7,32 @@ export function clamp(n: number, min: number, max: number) {
7
exportfunctionsum(...args: number[]|number[][]){
8
returnflattenArrayable(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
+ */
+exportfunctionlerp(min: number,max: number,t: number){
+constinterpolation=clamp(t,0.0,1.0)
+returnmin+(max-min)*interpolation
+}
+ * Linearly remaps a clamped value from its source range [`inMin`, `inMax`] to the destination range [`outMin`, `outMax`]
+ * const value = remap(0.5, 0, 1, 200, 400) // value will be 300
+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