Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isInRange

Checks if a number is within the given inclusive range.

TypeScript
Copied!
1/**
2 * Checks if a number is within the given inclusive range.
3 *
4 * @param num - The number to check.
5 * @param min - The minimum allowed value.
6 * @param max - The maximum allowed value.
7 * @returns True if num is between min and max (inclusive), false otherwise.
8 * @throws If min is greater than max.
9 */
10export function isInRange(num: number, min: number, max: number): boolean {
11  if (min > max) {
12    throw new Error('"min" should not be greater than "max"');
13  }
14  return num >= min && num <= max;
15}
  • Inclusive Range Check

    Explicitly includes both bounds (min and max), which aligns with common expectations in range validation.

  • Input Validation

    Throws a clear error if min > max, helping catch logical errors early.

  • Straightforward Logic

    Simple comparison ensures high readability and low cognitive overhead.

  • Reusable and Deterministic

    Stateless and consistent, making it easy to reuse across different parts of an application.

Tests | Examples

TypeScript
Copied!
1test('isInRange - inside range', () => {
2  expect(isInRange(5, 1, 10)).toBe(true);
3});
4
5test('isInRange - on lower bound', () => {
6  expect(isInRange(1, 1, 10)).toBe(true);
7});
8
9test('isInRange - on upper bound', () => {
10  expect(isInRange(10, 1, 10)).toBe(true);
11});
12
13test('isInRange - below range', () => {
14  expect(isInRange(0, 1, 10)).toBe(false);
15});
16
17test('isInRange - above range', () => {
18  expect(isInRange(11, 1, 10)).toBe(false);
19});
20
21test('isInRange - throws if min > max', () => {
22  expect(() => isInRange(5, 10, 1)).toThrow('"min" should not be greater than "max"');
23});

Common Use Cases

  • Form Input Validation

    Ensure user input (e.g., age, quantity, rating) falls within a defined acceptable range.

  • Configuration and Settings Enforcement

    Validate that numeric configuration values stay within safe or allowed limits.

  • UI Logic and Conditional Rendering

    Control layout or visibility based on screen width, scroll position, or zoom level thresholds.

  • Game Rules and Boundaries

    Check whether a character or object is within allowed coordinates, health levels, or time limits.

  • Data Filtering

    Filter or highlight items that fall within a certain numeric range (e.g. price, duration, score).

Codebase: Utilities -> Numbers -> isInRange | Yevhen Klymentiev