Skip to content

Commit e8fb252

Browse files
committed
feat(utils): added a withinRange util for number validation
1 parent 1832e69 commit e8fb252

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { withinRange } from "../withinRange";
2+
3+
describe("withinRange", () => {
4+
it("should return the value if the min or max values are undefined", () => {
5+
expect(withinRange(100, undefined, undefined)).toBe(100);
6+
expect(withinRange(0, undefined, undefined)).toBe(0);
7+
expect(withinRange(-100, undefined, undefined)).toBe(-100);
8+
});
9+
10+
it("should return the correct value based on the min and max values", () => {
11+
expect(withinRange(0, 0, 10)).toBe(0);
12+
expect(withinRange(-1, 0, 10)).toBe(0);
13+
expect(withinRange(-0.00000001, 0, 10)).toBe(0);
14+
expect(withinRange(20, 0, 20)).toBe(20);
15+
expect(withinRange(20, 0, 19)).toBe(19);
16+
expect(withinRange(10.5, 10, 11)).toBe(10.5);
17+
expect(withinRange(10.5, 9, 10)).toBe(10);
18+
});
19+
});

packages/utils/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ export * from "./throttle";
2121
export * from "./loop";
2222
export * from "./getPercentage";
2323
export * from "./nearest";
24+
export * from "./withinRange";
2425

2526
export * from "./useEnsuredRef";
2627
export * from "./useIsomorphicLayoutEffect";

packages/utils/src/withinRange.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* A simple util that will ensure that a number is within the optional min and max values.
3+
*
4+
* @param value The number to ensure that is within the range
5+
* @param min The optional min value
6+
* @param max The optional max value
7+
* @return the updated value
8+
*/
9+
export function withinRange(
10+
value: number,
11+
min: number | undefined,
12+
max: number | undefined
13+
): number {
14+
let nextValue = value;
15+
if (typeof min === "number") {
16+
nextValue = Math.max(min, nextValue);
17+
}
18+
19+
if (typeof max === "number") {
20+
nextValue = Math.min(max, nextValue);
21+
}
22+
23+
return nextValue;
24+
}

0 commit comments

Comments
 (0)