diff --git a/.changeset/olive-lobsters-give.md b/.changeset/olive-lobsters-give.md new file mode 100644 index 0000000..9657bfc --- /dev/null +++ b/.changeset/olive-lobsters-give.md @@ -0,0 +1,5 @@ +--- +"@giraugh/tools": minor +--- + +Add clamp utility to math module diff --git a/lib/math/clamp.ts b/lib/math/clamp.ts new file mode 100644 index 0000000..658d6d7 --- /dev/null +++ b/lib/math/clamp.ts @@ -0,0 +1,31 @@ +/** + * Return a value that is clamped between two inclusive bounds. + * @param value the value to clamp + * @param min the minimum bound + * @param max the maximum bound + * @returns returns `value` if within bounds, otherwise the closest bound + * + * @example + * clamp(10, 3, 12) === 10 + * clamp(1, 3, 12) === 3 + * clamp(20, 3, 12) === 12 + */ +export const clamp = (value: number, min: number, max: number): number => + Math.min(max, Math.max(min, value)) + +// Tests +if (import.meta.vitest) { + const { expect, it } = import.meta.vitest + + it('works for example 1', () => { + expect(clamp(10, 3, 12)).toBe(10) + }) + + it('works for example 2', () => { + expect(clamp(1, 3, 12)).toBe(3) + }) + + it('works for example 2', () => { + expect(clamp(20, 3, 12)).toBe(12) + }) +} diff --git a/lib/math/index.ts b/lib/math/index.ts index ae70e89..d0b448a 100644 --- a/lib/math/index.ts +++ b/lib/math/index.ts @@ -2,3 +2,4 @@ export * from './sum' export * from './product' export * from './constants' export * from './randomInt' +export * from './clamp'