From 8515bff983c6a71204a7431903a28975a1cd07f0 Mon Sep 17 00:00:00 2001 From: robonen Date: Wed, 10 Apr 2024 16:51:09 +0700 Subject: [PATCH] feat(packages/stdlib): math/clamp util --- packages/stdlib/src/index.ts | 1 + packages/stdlib/src/math/clamp/index.test.ts | 22 ++++++++++++++++++++ packages/stdlib/src/math/clamp/index.ts | 3 +++ packages/stdlib/src/math/index.ts | 1 + 4 files changed, 27 insertions(+) create mode 100644 packages/stdlib/src/index.ts create mode 100644 packages/stdlib/src/math/clamp/index.test.ts create mode 100644 packages/stdlib/src/math/clamp/index.ts create mode 100644 packages/stdlib/src/math/index.ts diff --git a/packages/stdlib/src/index.ts b/packages/stdlib/src/index.ts new file mode 100644 index 0000000..444cc89 --- /dev/null +++ b/packages/stdlib/src/index.ts @@ -0,0 +1 @@ +export * from './math'; \ No newline at end of file diff --git a/packages/stdlib/src/math/clamp/index.test.ts b/packages/stdlib/src/math/clamp/index.test.ts new file mode 100644 index 0000000..54157a4 --- /dev/null +++ b/packages/stdlib/src/math/clamp/index.test.ts @@ -0,0 +1,22 @@ +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 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 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); + }); +}); \ No newline at end of file diff --git a/packages/stdlib/src/math/clamp/index.ts b/packages/stdlib/src/math/clamp/index.ts new file mode 100644 index 0000000..29f49f6 --- /dev/null +++ b/packages/stdlib/src/math/clamp/index.ts @@ -0,0 +1,3 @@ +export function clamp(value: number, min: number, max: number): number { + return Math.min(Math.max(value, min), max); +} \ No newline at end of file diff --git a/packages/stdlib/src/math/index.ts b/packages/stdlib/src/math/index.ts new file mode 100644 index 0000000..0244181 --- /dev/null +++ b/packages/stdlib/src/math/index.ts @@ -0,0 +1 @@ +export * from './clamp'; \ No newline at end of file