diff --git a/src/utils/clamp.test.ts b/src/utils/clamp.test.ts new file mode 100644 index 0000000..a06fa57 --- /dev/null +++ b/src/utils/clamp.test.ts @@ -0,0 +1,38 @@ +import { describe, it, expect } from 'vitest'; +import { clamp } from './clamp'; + +describe('clamp', () => { + it('returns value when within range', () => { + expect(clamp(5, 1, 10)).toBe(5); + }); + + it('returns min when value is below min', () => { + expect(clamp(-2, 0, 8)).toBe(0); + }); + + it('returns max when value is above max', () => { + expect(clamp(100, 0, 50)).toBe(50); + }); + + it('returns min when value equals min', () => { + expect(clamp(3, 3, 6)).toBe(3); + }); + + it('returns max when value equals max', () => { + expect(clamp(6, 3, 6)).toBe(6); + }); + + it('works for negative bounds', () => { + expect(clamp(-5, -10, -1)).toBe(-5); + expect(clamp(-15, -10, -1)).toBe(-10); + expect(clamp(0, -10, -1)).toBe(-1); + }); + + it('returns value when min equals max and value equals both', () => { + expect(clamp(7, 7, 7)).toBe(7); + }); + + it('throws error if min > max', () => { + expect(() => clamp(5, 10, 2)).toThrow('min must be less than or equal to max'); + }); +}); diff --git a/src/utils/clamp.ts b/src/utils/clamp.ts new file mode 100644 index 0000000..5158474 --- /dev/null +++ b/src/utils/clamp.ts @@ -0,0 +1,16 @@ +/** + * Clamps a number between the provided min and max bounds. + * If value < min, returns min. If value > max, returns max. Otherwise, returns value. + * @param value - The number to clamp + * @param min - The lower bound + * @param max - The upper bound + * @returns The clamped value + */ +export function clamp(value: number, min: number, max: number): number { + if (min > max) { + throw new Error('min must be less than or equal to max'); + } + if (value < min) return min; + if (value > max) return max; + return value; +}