Created
June 9, 2022 14:11
-
-
Save balsama/444869bdeee087d05ed8185f4a3c873d to your computer and use it in GitHub Desktop.
Function to convert a value in a range to an equivalent value in a different range.
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
<?php | |
function rangeConverter( | |
int $input, | |
int $inputRangeMin, | |
int $inputRangeMax, | |
int $outputRangeMin = 0, | |
int $outputRangeMax = 100 | |
) :int | |
{ | |
if ($inputRangeMax <= $inputRangeMin) { | |
throw new \http\Exception\InvalidArgumentException('$inputRangeMax must be greater than $inputRangeMin'); | |
} | |
if ($outputRangeMax <= $outputRangeMin) { | |
throw new \http\Exception\InvalidArgumentException('$outputRangeMax must be greater than $outputRangeMin'); | |
} | |
if ($input < $inputRangeMin) { | |
throw new \http\Exception\InvalidArgumentException('$input must be greater than $inputRangeMin'); | |
} | |
if ($input > $inputRangeMax) { | |
throw new \http\Exception\InvalidArgumentException('$input must be less than $inputRangeMax'); | |
} | |
return ( | |
($outputRangeMax - $outputRangeMin) | |
* | |
( | |
($input - $inputRangeMin) | |
/ | |
($inputRangeMax - $inputRangeMin) | |
) | |
) | |
+ | |
$outputRangeMin; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment