Last active
November 20, 2021 16:01
-
-
Save josfaber/c7f00e0f76a95b15f7c2f567f9a6cc60 to your computer and use it in GitHub Desktop.
number utils
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
/** | |
* return random int in range | |
*/ | |
this.randInt = function (min, max) { | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
} | |
/** | |
* return random float in range | |
*/ | |
function randFloat (min, max) { | |
return Math.random() * (max - min) + min; | |
} | |
/** | |
* degrees to radians | |
*/ | |
function degToRad(deg) { | |
return deg*(Math.PI/180); | |
} | |
/** | |
* radians to degrees | |
*/ | |
function radToDeg(rad) { | |
return rad/(Math.PI/180); | |
} | |
/** | |
* returns the fraction behind the flaoting point of a float | |
*/ | |
function returnFloat(n) { | |
return n - Math.floor(n); | |
} | |
/** | |
* returns a value between 0 and 1 that represents the given value in the given range | |
*/ | |
function normalize(value, minimum, maximum) { | |
return (value - minimum) / (maximum - minimum); | |
} | |
/** | |
* returns the value in the given range for a representing normalized value | |
* (it's normalize, but the other way around) | |
*/ | |
function interpolate (normValue, minimum, maximum) { | |
return minimum + (maximum - minimum) * normValue; | |
} | |
/** | |
* returns the mapped value in range 2, given value 1 in range 1 | |
* (it's normalize, and than interpolate in a new range) | |
*/ | |
function map(value, min1, max1, min2, max2) { | |
return interpolate( normalize(value, min1, max1), min2, max2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment