Skip to content

Instantly share code, notes, and snippets.

@ishan-marikar
Forked from du5rte/ratios.js
Created July 25, 2018 10:35
Show Gist options
  • Save ishan-marikar/47b4555edc9878dee2bd2a017c346336 to your computer and use it in GitHub Desktop.
Save ishan-marikar/47b4555edc9878dee2bd2a017c346336 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