UNPKG

object-shape-tester

Version:
47 lines (46 loc) 1.47 kB
import { ensureErrorAndPrependMessage, ensureMinMax, wrapInTry, } from '@augment-vir/common'; import { Type } from '@sinclair/typebox'; import { assertValidShape } from '../shape/check-shape.js'; import { defineShape } from '../shape/shape.js'; /** * Creates a shape that requires a number within the given range. By default, the range is * inclusive. See {@link RangeShapeParams} for how to change that. * * @category Shape * @example * * ```ts * import {rangeShape, checkValidShape} from 'object-shape-tester'; * * const myShape = rangeShape({min: 1, max: 10}); * * checkValidShape(1, myShape); // `true` * checkValidShape(0, myShape); // `false` * ``` */ export function rangeShape({ exclusiveMax, exclusiveMin, ...params }) { const { min, max } = ensureMinMax(params); const defaultValue = params.default ?? (max - min) / 2 + min; const shape = defineShape(Type.Number({ ...(exclusiveMin ? { exclusiveMinimum: min, } : { minimum: min, }), ...(exclusiveMax ? { exclusiveMaximum: max, } : { maximum: max, }), default: defaultValue, })); const error = wrapInTry(() => assertValidShape(defaultValue, shape)); if (error) { throw ensureErrorAndPrependMessage(error, 'Default range value is not within range.'); } return shape; }