From 65ba312f4cbe434c0de8e0477547c7e63a46bf1c Mon Sep 17 00:00:00 2001 From: robonen Date: Thu, 11 Apr 2024 00:10:52 +0700 Subject: [PATCH] refactor(packages/stdlib): add comments for math utils --- packages/stdlib/src/math/clamp/index.ts | 5 +++++ packages/stdlib/src/math/mapRange/index.ts | 7 ++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/stdlib/src/math/clamp/index.ts b/packages/stdlib/src/math/clamp/index.ts index 41cffde..b8532eb 100644 --- a/packages/stdlib/src/math/clamp/index.ts +++ b/packages/stdlib/src/math/clamp/index.ts @@ -7,5 +7,10 @@ * @returns {number} The clamped number */ export function clamp(value: number, min: number, max: number): number { + // The clamp function takes a value, a minimum, and a maximum as parameters. + // It ensures that the value falls within the range defined by the minimum and maximum values. + // If the value is less than the minimum, it returns the minimum value. + // If the value is greater than the maximum, it returns the maximum value. + // Otherwise, it returns the original value. return Math.min(Math.max(value, min), max); } diff --git a/packages/stdlib/src/math/mapRange/index.ts b/packages/stdlib/src/math/mapRange/index.ts index cc9cddf..f82dd41 100644 --- a/packages/stdlib/src/math/mapRange/index.ts +++ b/packages/stdlib/src/math/mapRange/index.ts @@ -11,8 +11,13 @@ import { clamp } from "../clamp"; * @returns {number} The mapped value */ export function mapRange(value: number, in_min: number, in_max: number, out_min: number, out_max: number): number { + // Zero input range means invalid input, so return lowest output range value if (in_min === in_max) return out_min; - return (clamp(value, in_min, in_max) - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; + // To ensure the value is within the input range, clamp it + const clampedValue = clamp(value, in_min, in_max); + + // Finally, map the value from the input range to the output range + return (clampedValue - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } \ No newline at end of file