|
| 1 | +/** |
| 2 | + * Translates a value from one range to another. |
| 3 | + * This is useful in scenarios where you need to map a value from one scale |
| 4 | + * to another, such as converting a temperature from Celsius to Fahrenheit, |
| 5 | + * or mapping a slider value to a different range. |
| 6 | + * |
| 7 | + * @param {Object} params - The parameters for the translation. |
| 8 | + * @param {number} params.inputMin - The minimum value of the input range. |
| 9 | + * @param {number} params.inputMax - The maximum value of the input range. |
| 10 | + * @param {number} params.outputMin - The minimum value of the output range. |
| 11 | + * @param {number} params.outputMax - The maximum value of the output range. |
| 12 | + * @param {number} params.value - The value to be translated. |
| 13 | + * @returns {number} - The translated value, constrained within the output range. |
| 14 | + * |
| 15 | + * * @example |
| 16 | + * // Translates 50 from the range [0, 100] to the range [5, 10] |
| 17 | + * const output = translateValue({inputMin: 0, inputMax: 100, outputMin: 5, outputMax: 10, value: 50}); |
| 18 | + * console.log(output); // 7.5 |
| 19 | + */ |
| 20 | +export const translateValue = ({ |
| 21 | + inputMin, |
| 22 | + inputMax, |
| 23 | + outputMin, |
| 24 | + outputMax, |
| 25 | + value, |
| 26 | +}: { |
| 27 | + inputMin: number; |
| 28 | + inputMax: number; |
| 29 | + outputMin: number; |
| 30 | + outputMax: number; |
| 31 | + value: number; |
| 32 | +}): number => { |
| 33 | + // Calculate Input Range |
| 34 | + const inputRange = inputMax - inputMin; |
| 35 | + // Calculate Output Range |
| 36 | + const outputRange = outputMax - outputMin; |
| 37 | + // Scale the Input Value |
| 38 | + const scaledInputValue = (value - inputMin) / inputRange; |
| 39 | + // Translate to Output Range |
| 40 | + let outputValue = outputMin + scaledInputValue * outputRange; |
| 41 | + // Constrain the Output Value |
| 42 | + outputValue = Math.min(outputMax, Math.max(outputMin, outputValue)); |
| 43 | + |
| 44 | + return outputValue; |
| 45 | +}; |
0 commit comments