-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
MathUtil.ts
32 lines (29 loc) · 1022 Bytes
/
MathUtil.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
export const MathUtil = {
/**
* Interpolates a value from one range to another
* @param inputRange - number array of length 2 that represents the original range
* @param outputRange - number array of length 2 that represents the new range
* @param value - the value to interpolation
* @returns
*/
interpolate(inputRange: number[], outputRange: number[], value: number) {
if (inputRange.length !== 2 || outputRange.length !== 2) {
throw new Error('inputRange and outputRange must be an array of length 2')
}
const originalRangeMin = inputRange[0] || 0
const originalRangeMax = inputRange[1] || 0
const newRangeMin = outputRange[0] || 0
const newRangeMax = outputRange[1] || 0
if (value < originalRangeMin) {
return newRangeMin
}
if (value > originalRangeMax) {
return newRangeMax
}
return (
((newRangeMax - newRangeMin) / (originalRangeMax - originalRangeMin)) *
(value - originalRangeMin) +
newRangeMin
)
}
}