mirror of
https://github.com/robonen/tools.git
synced 2026-03-20 02:44:45 +00:00
refactor(packages/stdlib): add doc, update tests
This commit is contained in:
@@ -2,21 +2,45 @@ import { describe,it, expect } from 'vitest';
|
||||
import { clamp } from '.';
|
||||
|
||||
describe('clamp', () => {
|
||||
it('should return the value itself if it is within the range', () => {
|
||||
expect(clamp(5, 0, 10)).toBe(5);
|
||||
expect(clamp(-3, -5, 5)).toBe(-3);
|
||||
expect(clamp(0, -10, 10)).toBe(0);
|
||||
it('should clamp a value within the given range', () => {
|
||||
// value < min
|
||||
expect(clamp(-10, 0, 100)).toBe(0);
|
||||
|
||||
// value > max
|
||||
expect(clamp(200, 0, 100)).toBe(100);
|
||||
|
||||
// value within range
|
||||
expect(clamp(50, 0, 100)).toBe(50);
|
||||
|
||||
// value at min
|
||||
expect(clamp(0, 0, 100)).toBe(0);
|
||||
|
||||
// value at max
|
||||
expect(clamp(100, 0, 100)).toBe(100);
|
||||
|
||||
// value at midpoint
|
||||
expect(clamp(50, 100, 100)).toBe(100);
|
||||
});
|
||||
|
||||
it('should return the minimum value if the value is less than the minimum', () => {
|
||||
expect(clamp(-10, 0, 10)).toBe(0);
|
||||
expect(clamp(-100, -50, 50)).toBe(-50);
|
||||
expect(clamp(-5, -5, 5)).toBe(-5);
|
||||
it('should handle floating-point numbers correctly', () => {
|
||||
// floating-point value within range
|
||||
expect(clamp(3.14, 0, 5)).toBe(3.14);
|
||||
|
||||
// floating-point value < min
|
||||
expect(clamp(-1.5, 0, 10)).toBe(0);
|
||||
|
||||
// floating-point value > max
|
||||
expect(clamp(15.75, 0, 10)).toBe(10);
|
||||
});
|
||||
|
||||
it('should return the maximum value if the value is greater than the maximum', () => {
|
||||
expect(clamp(15, 0, 10)).toBe(10);
|
||||
expect(clamp(100, -50, 50)).toBe(50);
|
||||
expect(clamp(10, -5, 5)).toBe(5);
|
||||
it('should handle edge cases', () => {
|
||||
// all values are the same
|
||||
expect(clamp(5, 5, 5)).toBe(5);
|
||||
|
||||
// min > max
|
||||
expect(clamp(10, 100, 50)).toBe(50);
|
||||
|
||||
// negative range and value
|
||||
expect(clamp(-10, -100, -5)).toBe(-10);
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,11 @@
|
||||
/**
|
||||
* Clamps a number between a minimum and maximum value
|
||||
*
|
||||
* @param {number} value The number to clamp
|
||||
* @param {number} min Minimum value
|
||||
* @param {number} max Maximum value
|
||||
* @returns {number} The clamped number
|
||||
*/
|
||||
export function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(Math.max(value, min), max);
|
||||
}
|
||||
Reference in New Issue
Block a user