-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #30 from giraugh/feat/clamp
`clamp` utility for clamping a value between two bounds
- Loading branch information
Showing
3 changed files
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
"@giraugh/tools": minor | ||
--- | ||
|
||
Add clamp utility to math module |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters