From 6eb597ad315c3d63a4b3a39371128d746c044bbf Mon Sep 17 00:00:00 2001 From: Ewan Breakey Date: Sun, 10 Sep 2023 15:53:16 +1000 Subject: [PATCH 1/3] Add clamp utility --- lib/math/clamp.ts | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 lib/math/clamp.ts 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) + }) +} From e4aec21eb226147ddb3eb14feab5cecb4052f1ca Mon Sep 17 00:00:00 2001 From: Ewan Breakey Date: Sun, 10 Sep 2023 15:54:33 +1000 Subject: [PATCH 2/3] Add changeset for clamp --- .changeset/olive-lobsters-give.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/olive-lobsters-give.md 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 From da4a9d61fc66624a47b36710c531b928b1d8cab8 Mon Sep 17 00:00:00 2001 From: Ewan Breakey Date: Sun, 10 Sep 2023 15:56:24 +1000 Subject: [PATCH 3/3] Add clamp to barrel --- lib/math/index.ts | 1 + 1 file changed, 1 insertion(+) 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'