Created
May 11, 2024 00:22
-
-
Save afraser/40a3a6e6f51343681a63d051d211d2f3 to your computer and use it in GitHub Desktop.
Scales a number expected to be in the range [inMin-inMax] to a number in the range [outMin-outMax].
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Scales a number expected to be in the range [inMin-inMax] | |
to a number in the range [outMin-outMax] | |
eg: | |
rangeTransform(5, [0, 10], [0, 50]) | |
> 25 | |
NOTE: If num is outside of [inMin-inMax] the result will | |
also be outside [outMin-outMax]. | |
*/ | |
export default function rangeTransform( | |
num: number, | |
[inMin, inMax]: Tuple, | |
[outMin, outMax]: Tuple | |
) { | |
const rebase = num - inMin | |
const desiredRange = outMax - outMin | |
const inputRange = inMax - inMin | |
const scalingFactor = desiredRange / inputRange | |
return rebase * scalingFactor + outMin | |
} | |
type Tuple = [number, number] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment