UNPKG

typia

Version:

Superfast runtime validators with only one line

71 lines (70 loc) 2.31 kB
import { _randomMultiple } from "./_randomMultiple.mjs"; //#region src/internal/_randomInteger.ts const _randomInteger = (schema) => { const lower = getLowerBoundary(schema); const upper = getUpperBoundary(schema); const minimum = lower?.value ?? (upper === null ? 0 : upper.value - 100); const maximum = upper?.value ?? (lower === null ? 100 : lower.value + 100); if (minimum > maximum) throw new Error("Minimum value is greater than maximum value."); return schema.multipleOf === void 0 ? scalar({ minimum, maximum }) : _randomMultiple({ minimum, maximum, multipleOf: schema.multipleOf, exclusiveMinimum: lower?.exclusive ?? false, exclusiveMaximum: upper?.exclusive ?? false, integer: true }); }; const scalar = (props) => { const minimum = Math.ceil(props.minimum); const maximum = Math.floor(props.maximum); if (minimum > maximum) throw new Error("The integer range is empty."); return Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; }; const getLowerBoundary = (schema) => { const inclusive = schema.minimum === void 0 ? null : { value: schema.minimum, exclusive: false }; const exclusive = schema.exclusiveMinimum === void 0 ? null : { value: schema.exclusiveMinimum, exclusive: true }; const selected = selectBoundary(inclusive, exclusive, Math.max); if (selected === null) return null; return { value: selected.exclusive ? Math.floor(selected.value) + 1 : Math.ceil(selected.value), exclusive: false }; }; const getUpperBoundary = (schema) => { const inclusive = schema.maximum === void 0 ? null : { value: schema.maximum, exclusive: false }; const exclusive = schema.exclusiveMaximum === void 0 ? null : { value: schema.exclusiveMaximum, exclusive: true }; const selected = selectBoundary(inclusive, exclusive, Math.min); if (selected === null) return null; return { value: selected.exclusive ? Math.ceil(selected.value) - 1 : Math.floor(selected.value), exclusive: false }; }; const selectBoundary = (x, y, compare) => { if (x === null) return y; if (y === null) return x; if (x.value === y.value) return { value: x.value, exclusive: x.exclusive || y.exclusive }; return compare(x.value, y.value) === x.value ? x : y; }; //#endregion export { _randomInteger }; //# sourceMappingURL=_randomInteger.mjs.map