typia
Version:
Superfast runtime validators with only one line
75 lines • 3.09 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports._randomInteger = void 0;
const _randomMultiple_1 = require("./_randomMultiple");
const _randomInteger = (schema) => {
var _a, _b, _c, _d;
const lower = getLowerBoundary(schema);
const upper = getUpperBoundary(schema);
const minimum = (_a = lower === null || lower === void 0 ? void 0 : lower.value) !== null && _a !== void 0 ? _a : (upper === null ? 0 : upper.value - 100);
const maximum = (_b = upper === null || upper === void 0 ? void 0 : upper.value) !== null && _b !== void 0 ? _b : (lower === null ? 100 : lower.value + 100);
if (minimum > maximum)
throw new Error("Minimum value is greater than maximum value.");
return schema.multipleOf === undefined
? scalar({ minimum, maximum })
: (0, _randomMultiple_1._randomMultiple)({
minimum,
maximum,
multipleOf: schema.multipleOf,
exclusiveMinimum: (_c = lower === null || lower === void 0 ? void 0 : lower.exclusive) !== null && _c !== void 0 ? _c : false,
exclusiveMaximum: (_d = upper === null || upper === void 0 ? void 0 : upper.exclusive) !== null && _d !== void 0 ? _d : false,
integer: true,
});
};
exports._randomInteger = _randomInteger;
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 === undefined
? null
: { value: schema.minimum, exclusive: false };
const exclusive = schema.exclusiveMinimum === undefined
? 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 === undefined
? null
: { value: schema.maximum, exclusive: false };
const exclusive = schema.exclusiveMaximum === undefined
? 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;
};
//# sourceMappingURL=_randomInteger.js.map