-
-
Save ishan-marikar/47b4555edc9878dee2bd2a017c346336 to your computer and use it in GitHub Desktop.
Expand Ratios
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
// 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