Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
feat(utils): added a withinRange util for number validation
  • Loading branch information
mlaursen committed Nov 24, 2020
1 parent 1832e69 commit e8fb252
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
19 changes: 19 additions & 0 deletions packages/utils/src/__tests__/withinRange.ts
@@ -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);
});
});
1 change: 1 addition & 0 deletions packages/utils/src/index.ts
Expand Up @@ -21,6 +21,7 @@ export * from "./throttle";
export * from "./loop";
export * from "./getPercentage";
export * from "./nearest";
export * from "./withinRange";

export * from "./useEnsuredRef";
export * from "./useIsomorphicLayoutEffect";
Expand Down
24 changes: 24 additions & 0 deletions packages/utils/src/withinRange.ts
@@ -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;
}

0 comments on commit e8fb252

Please sign in to comment.