-
-
Notifications
You must be signed in to change notification settings - Fork 298
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(utils): added a withinRange util for number validation
- Loading branch information
Showing
3 changed files
with
44 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,19 @@ | ||
import { withinRange } from "../withinRange"; | ||
|
||
describe("withinRange", () => { | ||
it("should return the value if the min or max values are undefined", () => { | ||
expect(withinRange(100, undefined, undefined)).toBe(100); | ||
expect(withinRange(0, undefined, undefined)).toBe(0); | ||
expect(withinRange(-100, undefined, undefined)).toBe(-100); | ||
}); | ||
|
||
it("should return the correct value based on the min and max values", () => { | ||
expect(withinRange(0, 0, 10)).toBe(0); | ||
expect(withinRange(-1, 0, 10)).toBe(0); | ||
expect(withinRange(-0.00000001, 0, 10)).toBe(0); | ||
expect(withinRange(20, 0, 20)).toBe(20); | ||
expect(withinRange(20, 0, 19)).toBe(19); | ||
expect(withinRange(10.5, 10, 11)).toBe(10.5); | ||
expect(withinRange(10.5, 9, 10)).toBe(10); | ||
}); | ||
}); |
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
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,24 @@ | ||
/** | ||
* A simple util that will ensure that a number is within the optional min and max values. | ||
* | ||
* @param value The number to ensure that is within the range | ||
* @param min The optional min value | ||
* @param max The optional max value | ||
* @return the updated value | ||
*/ | ||
export function withinRange( | ||
value: number, | ||
min: number | undefined, | ||
max: number | undefined | ||
): number { | ||
let nextValue = value; | ||
if (typeof min === "number") { | ||
nextValue = Math.max(min, nextValue); | ||
} | ||
|
||
if (typeof max === "number") { | ||
nextValue = Math.min(max, nextValue); | ||
} | ||
|
||
return nextValue; | ||
} |