mirror of
https://github.com/robonen/tools.git
synced 2026-03-20 02:44:45 +00:00
feat(packages/stdlib): math/clamp util
This commit is contained in:
1
packages/stdlib/src/index.ts
Normal file
1
packages/stdlib/src/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from './math';
|
||||||
22
packages/stdlib/src/math/clamp/index.test.ts
Normal file
22
packages/stdlib/src/math/clamp/index.test.ts
Normal file
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
3
packages/stdlib/src/math/clamp/index.ts
Normal file
3
packages/stdlib/src/math/clamp/index.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export function clamp(value: number, min: number, max: number): number {
|
||||||
|
return Math.min(Math.max(value, min), max);
|
||||||
|
}
|
||||||
1
packages/stdlib/src/math/index.ts
Normal file
1
packages/stdlib/src/math/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from './clamp';
|
||||||
Reference in New Issue
Block a user