Skip to content

Instantly share code, notes, and snippets.

@du5rte
Last active July 25, 2018 10:35
Show Gist options
  • Save du5rte/27f7cbb66bd04a509e1b2018d25d5ca8 to your computer and use it in GitHub Desktop.
Save du5rte/27f7cbb66bd04a509e1b2018d25d5ca8 to your computer and use it in GitHub Desktop.
Expand Ratios
// https://stackoverflow.com/questions/14224535/scaling-between-two-number-ranges
function withinRange(val, { min, max }) {
return (
val > max
? max
: val < min
? min
: val
);
}
function ratioToValue(ratio, { min, max }) {
const value = ratio * (max - min) + min;
return withinRange(value, { min, max });
}
function valueToRatio(value, { min=0, max=1 }={}) {
const ratio = (value - min) / (max - min);
return withinRange(ratio, { min: 0, max: 1 });
}
console.log(
valueToRatio(1, { min: 1, max: 3 })
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment