isBetween function
Checks whether a number lies between two bounds.
ts
import { isBetween } from 'utils';Signature
ts
export function isBetween(value: number, min: number, max: number, isInclusive = true): booleanParameters
| Name | Description |
|---|---|
value | The number to check. |
min | The lower bound. |
max | The upper bound. |
isInclusive | Whether the bounds themselves are between. Defaults to true. |
Returns
true when value lies within the bounds.
Example
ts
isBetween(10, 0, 10); // true
isBetween(10, 0, 10, false); // falseTests
Line coverage: 100 %.
- ✅ checks 5 in [0, 10] inclusively as true
- ✅ checks 0 in [0, 10] inclusively as true
- ✅ checks 10 in [0, 10] inclusively as true
- ✅ checks 11 in [0, 10] inclusively as false
- ✅ excludes the bounds when not inclusive
Source
src/math/is-between.ts (on GitHub)
Source code
ts
/**
* Checks whether a number lies between two bounds.
*
* @param value - The number to check.
* @param min - The lower bound.
* @param max - The upper bound.
* @param isInclusive - Whether the bounds themselves are between. Defaults to `true`.
* @returns `true` when `value` lies within the bounds.
* @example
* isBetween(10, 0, 10); // true
* isBetween(10, 0, 10, false); // false
*/
export function isBetween(value: number, min: number, max: number, isInclusive = true): boolean {
return isInclusive ? value >= min && value <= max : value > min && value < max;
}Test file
ts
import { isBetween } from './is-between';
describe(isBetween, () => {
it.for([
[5, 0, 10, true],
[0, 0, 10, true],
[10, 0, 10, true],
[11, 0, 10, false],
] as const)('checks %s in [%s, %s] inclusively as %s', ([value, min, max, expected]) => {
expect(isBetween(value, min, max, true)).toBe(expected);
});
it('excludes the bounds when not inclusive', () => {
expect(isBetween(0, 0, 10, false)).toBe(false);
expect(isBetween(10, 0, 10, false)).toBe(false);
expect(isBetween(5, 0, 10, false)).toBe(true);
});
});Keywords: is, between, math, function