Skip to content

Instantly share code, notes, and snippets.

@afraser
Created May 11, 2024 00:22
Show Gist options
  • Save afraser/40a3a6e6f51343681a63d051d211d2f3 to your computer and use it in GitHub Desktop.
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].
/**
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