Created
August 11, 2021 09:55
-
-
Save JakobTischler/e413675838d3a549caaa9e0dae82de4c to your computer and use it in GitHub Desktop.
Normalizes a `value` between `min` and `max` and then casts it onto a range between `rangeMin` (defaults to 0) and `rangeMax` (defaults to 1). The initial normalization can be clamped between 0 and 1 (`clamp`, defaults true). The return value describes where `value` would lay if `min` and `max` were represented by the `rangeMin` and `rangeMax` r…
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
/** | |
* Normalizes a `value` between `min` and `max` and then casts it onto a range between `rangeMin` | |
* (defaults to 0) and `rangeMax` (defaults to 1). The initial normalization can be clamped between | |
* 0 and 1 (`clamp`, defaults true). The return value describes where `value` would lay if `min` | |
* and `max` were represented by the `rangeMin` and `rangeMax` range. | |
* | |
* Read as: "value is to min and max as result is to rangeMin and rangeMax" | |
* | |
* @param {number} value The value to cast. | |
* @param {number} min The lower value of the normalization set. `min < max` must be true. | |
* @param {number} max The upper value of the normalization set. `max > min` must be true. | |
* @param {number} [rangeMin] The lower value of the representation range. Defaults to 0. | |
* @param {number} [rangeMax] The upper value of the representation range. Defaults to 1. | |
* @param {boolean} [clamp] If true, the normalization is clamped to between 0 and 1. Defaults to true. | |
* @returns {number} The position the value would have if `min` and `max` were `rangeMin` and `rangeMax`. | |
* @example value = 10, min = -20, max = 20, rangeMin = 0, rangeMax = 1, clamp = true. Returns: 0.75 | |
* @example value = 10, min = -20, max = 20, rangeMin = -1, rangeMax = 1, clamp = true. Returns: 0.5 | |
* @example value = -30, min = -20, max = 20, rangeMin = 0, rangeMax = 10, clamp = false. Returns: -2.5 | |
*/ | |
const normalizeInRange = ((value, min, max, rangeMin = 0.0, rangeMax = 1.0, clamp = false) => { | |
let n = (value - min) / (max - min); | |
if (clamp) { | |
n = Math.max(Math.min(n, 1.0), 0.0); | |
} | |
const result = rangeMin + n * (rangeMax - rangeMin); | |
// Test logging | |
console.group('normalizeInRange'); | |
console.log({ value, min, max, rangeMin, rangeMax, clamp }); | |
console.log('Result:', result); | |
console.groupEnd(); | |
return result; | |
})(0.75, -4, 4, 100, 200); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment