Skip to content

Commit

Permalink
Limit number function update
Browse files Browse the repository at this point in the history
  • Loading branch information
knownout committed May 10, 2022
1 parent 18402fd commit 6dcdfe1
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 11 deletions.
15 changes: 8 additions & 7 deletions package/bin/functions/limitNumber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,22 @@
/**
* Utility function to limit a certain number to an upper and lower bound.
* @param {number} value certain number.
* @param {{top?: number, bottom?: number}} options set lower or upper bound.
* @param top upper bound.
* @param bottom lower bound.
* @return {number} generated number.
*/
function limitNumber (value: number, options: { top?: number, bottom?: number }): number {
function limitNumber (value: number, top?: number | null, bottom?: number | null): number {
const isNumber = (value: any) => Number.isInteger(value) || Number.isFinite(value);

// Show warning if upper and lower bounds are the same
if (options.top === options.bottom) console.warn("It makes no sense to "
if (isNumber(top) && top === bottom) console.warn("It makes no sense to "
+ "set the value of the lower and upper limits, in this case the function will not "
+ "work correctly");

let result = value;

// @ts-ignore
if (Number.isInteger(options.bottom) && result < options.bottom) result = options.bottom;
// @ts-ignore
if (Number.isInteger(options.top) && result > options.top) result = options.top;
if (isNumber(bottom) && result < bottom) result = bottom;
if (isNumber(top) && result > top) result = top;

return result;
}
Expand Down
9 changes: 6 additions & 3 deletions package/bin/functions/tests/limitNumber.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@
import limitNumber from "../limitNumber";

it("limitNumber function test", () => {
expect(limitNumber(-12, { bottom: 0, top: 1 })).toEqual(0);
expect(limitNumber(12, { bottom: 2, top: 10 })).toEqual(10);
expect(limitNumber(-12, 1, 0)).toEqual(0);
expect(limitNumber(12, 10, 2)).toEqual(10);

expect(limitNumber(10, { bottom: 2, top: 1 })).toEqual(1);
expect(limitNumber(10, 1, 2)).toEqual(1);

expect(limitNumber(-3, null, -2)).toEqual(-2);
expect(limitNumber(12, null, -2)).toEqual(12);
});
2 changes: 1 addition & 1 deletion package/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@knownout/lib",
"version": "0.0.9",
"version": "0.1.0",
"author": "Alexandr <re-knownout> knownout@hotmail.com",
"license": "AGPL-3.0",
"description": "Utility functions library",
Expand Down

0 comments on commit 6dcdfe1

Please sign in to comment.