isWithin
The isWithin utility checks if a numeric value falls within a specified inclusive range. It is perfect for validating inputs, checking UI bounds, or coordinating logic that requires values to be between certain limits.
Implementation
View Source Code
ts
import { isNumber } from './isNumber';
/**
* Checks if a value is within a specified range.
*
* @example
* ```ts
* isWithin(1, 0, 1); // true
* isWithin(1, 0, 1, false); // false
* isWithin(0.5, 0, 1); // true
* ```
*
* @param arg - The value to be checked.
* @param min - The minimum value of the range.
* @param max - The maximum value of the range.
* @param inclusive - Whether the range is inclusive or exclusive. (defaults: `true`).
*
* @returns `true` if the value is in between, else `false`.
*/
export function isWithin(arg: unknown, min: unknown, max: unknown, inclusive = true): boolean {
if (!isNumber(arg) || !isNumber(min) || !isNumber(max)) {
return false;
}
return inclusive ? arg >= min && arg <= max : arg > min && arg < max;
}
export const IS_WITHIN_ERROR_MSG = 'Expected a number within a specified range';Features
- Isomorphic: Works in both Browser and Node.js.
- Inclusive Range: Considers both the minimum and maximum values as valid (within the range).
- Robust: Automatically handles cases where
minis greater thanmaxby swapping them. - Type-safe: Properly typed for numeric inputs.
API
ts
function isWithin(value: number, min: number, max: number): boolean;Parameters
value: The number to check.min: The lower bound of the range.max: The upper bound of the range.
Returns
trueif the value is betweenminandmax(inclusive); otherwise,false.
Examples
Basic Usage
ts
import { isWithin } from '@vielzeug/toolkit';
isWithin(5, 0, 10); // true
isWithin(0, 0, 10); // true
isWithin(10, 0, 10); // true
isWithin(-5, 0, 10); // false
isWithin(15, 0, 10); // falseImplementation Notes
- Returns
trueifvalue >= min && value <= max. - Swaps
minandmaxinternally ifmin > maxto ensure consistent behavior. - Throws nothing; returns
falsefor non-numeric inputs if TypeScript checks are bypassed.
See Also
- clamp: Restrict a number to a specific range (returning the clamped value).
- isNumber: Check if a value is a number.
- isPositive: Check if a number is greater than zero.