Skip to content

Commit

Permalink
Merge pull request #30 from giraugh/feat/clamp
Browse files Browse the repository at this point in the history
`clamp` utility for clamping a value between two bounds
  • Loading branch information
giraugh authored Sep 10, 2023
2 parents 15531db + da4a9d6 commit 2d9967a
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/olive-lobsters-give.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@giraugh/tools": minor
---

Add clamp utility to math module
31 changes: 31 additions & 0 deletions lib/math/clamp.ts
Original file line number Diff line number Diff line change
@@ -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)
})
}
1 change: 1 addition & 0 deletions lib/math/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from './sum'
export * from './product'
export * from './constants'
export * from './randomInt'
export * from './clamp'

0 comments on commit 2d9967a

Please sign in to comment.