typedash
Version:
modern, type-safe collection of utility functions
1 lines • 2.37 kB
Source Map (JSON)
{"version":3,"sources":["../../src/functions/clamp/clamp.ts"],"names":[],"mappings":";AA8BO,SAAS,MACd,OACA,OACA,SACQ;AACR,QAAM,CAAC,KAAK,GAAG,IAAI;AACnB,MAAI,MAAM,KAAK;AACb,UAAM,IAAI,WAAW,mBAAmB,GAAG,IAAI,GAAG,GAAG;AAAA,EACvD;AAEA,QAAM,EAAE,YAAY,KAAK,IAAI,WAAW,CAAC;AAEzC,SAAO;AAAA,IACL,MAAM,MAAM,KAAK,IAAI,KAAK,KAAK,IAAI,KAAK,KAAK,CAAC;AAAA,IAC9C,OAAO,MAAM,KAAK,IAAI,MAAM,GAAG,KAAK,IAAI,MAAM,GAAG,KAAK,CAAC;AAAA,IACvD,KAAK,MAAM,KAAK,IAAI,KAAK,KAAK,IAAI,MAAM,GAAG,KAAK,CAAC;AAAA,IACjD,KAAK,MAAM,KAAK,IAAI,MAAM,GAAG,KAAK,IAAI,KAAK,KAAK,CAAC;AAAA,EACnD,EAAE,SAA2C,EAAE;AACjD","sourcesContent":["import { CastToString } from '../../types';\n\ninterface ClampOptions {\n /**\n * Whether the clamping should be inclusive of the range.\n * @default true\n */\n inclusive?: boolean | 'min' | 'max';\n}\n\n/**\n * Clamps a number to a specified range.\n * @param value The number to clamp.\n * @param range The range to clamp to, as a tuple of min and max values.\n * @param options Optional parameters.\n * @param options.inclusive Whether the clamping should be inclusive of the min and/or max value.\n * - If `true`, the clamping is inclusive of both min and max.\n * - If `false`, the clamping is exclusive of both min and max.\n * - If `'min'`, the clamping is inclusive of the min value but exclusive of the max value.\n * - If `'max'`, the clamping is exclusive of the min value but inclusive of the max value.\n * @returns The clamped number.\n * @example\n * ```typescript\n * clamp(3, [1, 5]); // 3\n * clamp(5, [1, 5]); // 5\n * clamp(5, [1, 5], { inclusive: false }); // 4\n * clamp(1, [1, 5], { inclusive: 'max' }); // 5\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 clamp(\n value: number,\n range: readonly [min: number, max: number],\n options?: ClampOptions\n): number {\n const [min, max] = range;\n if (min > max) {\n throw new RangeError(`Invalid range: [${min},${max}]`);\n }\n\n const { inclusive = true } = options ?? {};\n\n return {\n true: () => Math.max(min, Math.min(max, value)),\n false: () => Math.max(min + 1, Math.min(max - 1, value)),\n min: () => Math.max(min, Math.min(max - 1, value)),\n max: () => Math.max(min + 1, Math.min(max, value)),\n }[inclusive as CastToString<typeof inclusive>]();\n}\n"]}