1
0
mirror of https://github.com/robonen/tools.git synced 2026-03-20 10:54:44 +00:00

feat(packages/stdlib): mapRange util

This commit is contained in:
2024-04-10 20:21:44 +07:00
parent 5280ace168
commit d8a9a62335
3 changed files with 66 additions and 1 deletions

View File

@@ -1 +1,2 @@
export * from './clamp'; export * from './clamp';
export * from './mapRange';

View File

@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest';
import { mapRange } from './index';
describe('mapRange', () => {
it('should map values from one range to another', () => {
// value at midpoint
expect(mapRange(5, 0, 10, 0, 100)).toBe(50);
// value at min
expect(mapRange(0, 0, 10, 0, 100)).toBe(0);
// value at max
expect(mapRange(10, 0, 10, 0, 100)).toBe(100);
// value outside range (below)
expect(mapRange(-5, 0, 10, 0, 100)).toBe(0);
// value outside range (above)
expect(mapRange(15, 0, 10, 0, 100)).toBe(100);
// value at midpoint of negative range
expect(mapRange(75, 50, 100, -50, 50)).toBe(0);
// value at midpoint of negative range
expect(mapRange(-25, -50, 0, 0, 100)).toBe(50);
});
it('should handle floating-point numbers correctly', () => {
// floating-point value
expect(mapRange(3.5, 0, 10, 0, 100)).toBe(35);
// positive floating-point ranges
expect(mapRange(1.25, 0, 2.5, 0, 100)).toBe(50);
// negative floating-point value
expect(mapRange(-2.5, -5, 0, 0, 100)).toBe(50);
// negative floating-point ranges
expect(mapRange(-1.25, -2.5, 0, 0, 100)).toBe(50);
});
it('should handle edge cases', () => {
// input range is zero (should return output min)
expect(mapRange(5, 0, 0, 0, 100)).toBe(0);
});
});

View File

@@ -0,0 +1,18 @@
import { clamp } from "../clamp";
/**
* Map a value from one range to another
*
* @param {number} value The value to map
* @param {number} in_min The minimum value of the input range
* @param {number} in_max The maximum value of the input range
* @param {number} out_min The minimum value of the output range
* @param {number} out_max The maximum value of the output range
* @returns {number} The mapped value
*/
export function mapRange(value: number, in_min: number, in_max: number, out_min: number, out_max: number): number {
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;
}