typedash
Version:
modern, type-safe collection of utility functions
1 lines • 2.3 kB
Source Map (JSON)
{"version":3,"sources":["../../src/functions/inRange/inRange.ts"],"names":[],"mappings":";AA8BO,SAAS,QACd,OACA,OACA,SACS;AACT,QAAM,CAAC,OAAO,GAAG,IAAI;AACrB,QAAM,EAAE,YAAY,QAAQ,IAAI,WAAW,CAAC;AAE5C,MAAI,QAAQ,KAAK;AACf,UAAM,IAAI,WAAW,mBAAmB,KAAK,IAAI,GAAG,GAAG;AAAA,EACzD;AAEA,SAAO;AAAA,IACL,MAAM,MAAM,SAAS,SAAS,SAAS;AAAA,IACvC,OAAO,MAAM,QAAQ,SAAS,QAAQ;AAAA,IACtC,OAAO,MAAM,SAAS,SAAS,QAAQ;AAAA,IACvC,KAAK,MAAM,QAAQ,SAAS,SAAS;AAAA,EACvC,EAAE,SAA2C,EAAE;AACjD","sourcesContent":["import { CastToString } from '../../types';\n\ninterface InRangeOptions {\n /**\n * Whether the range is inclusive of the end value.\n * @default 'start'\n */\n inclusive?: boolean | 'start' | 'end';\n}\n\n/**\n * Checks if a number is within a specified range.\n * @param value The number to check.\n * @param range The range to check against, as a tuple of start and end values.\n * @param options Optional parameters.\n * @param options.inclusive Whether the range is inclusive of the start and/or end value.\n * - If `true`, the range is inclusive of both start and end.\n * - If `false`, the range is exclusive of both start and end.\n * - If `'start'`, the range is inclusive of the start value but exclusive of the end value.\n * - If `'end'`, the range is exclusive of the start value but inclusive of the end value.\n * @returns `true` if the number is within the range, `false` otherwise.\n * @example\n * ```typescript\n * inRange(3, [1, 5]); // true\n * inRange(5, [1, 5]); // false\n * inRange(5, [1, 5], { inclusive: true }); // true\n * inRange(1, [1, 5], { inclusive: 'end' }); // false\n * ```\n */\n// eslint-disable-next-line consistent-return -- we have an exhaustive check, so we never get to the end of the function\nexport function inRange(\n value: number,\n range: readonly [start: number, end: number],\n options?: InRangeOptions\n): boolean {\n const [start, end] = range;\n const { inclusive = 'start' } = options ?? {};\n\n if (start > end) {\n throw new RangeError(`Invalid range: [${start},${end}]`);\n }\n\n return {\n true: () => value >= start && value <= end,\n false: () => value > start && value < end,\n start: () => value >= start && value < end,\n end: () => value > start && value <= end,\n }[inclusive as CastToString<typeof inclusive>]();\n}\n"]}