Last active
July 25, 2018 10:35
-
-
Save du5rte/27f7cbb66bd04a509e1b2018d25d5ca8 to your computer and use it in GitHub Desktop.
Expand Ratios
This file contains 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