From 80235bcc807f41f42e436985970e8f39dff48bc5 Mon Sep 17 00:00:00 2001 From: webdevcom01-cell Date: Thu, 30 Apr 2026 13:11:32 +0200 Subject: [PATCH 1/2] feat(clamp-function): SDLC [d1e9fa7c] --- src/utils/clamp.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 src/utils/clamp.ts 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; +} From 5a7ec98f5280d430ff66d3837373121c9eff0f7e Mon Sep 17 00:00:00 2001 From: webdevcom01-cell Date: Thu, 30 Apr 2026 13:11:33 +0200 Subject: [PATCH 2/2] test(clamp-function): SDLC [d1e9fa7c] --- src/utils/clamp.test.ts | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/utils/clamp.test.ts 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'); + }); +});