typia
Version:
Superfast runtime validators with only one line
63 lines • 3.16 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports._randomNumber = void 0;
const _randomMultiple_1 = require("./_randomMultiple");
const _randomNumber = (schema) => {
var _a, _b, _c, _d, _e, _f;
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,
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,
})
: (0, _randomMultiple_1._randomMultiple)({
minimum,
maximum,
multipleOf: schema.multipleOf,
exclusiveMinimum: (_e = lower === null || lower === void 0 ? void 0 : lower.exclusive) !== null && _e !== void 0 ? _e : false,
exclusiveMaximum: (_f = upper === null || upper === void 0 ? void 0 : upper.exclusive) !== null && _f !== void 0 ? _f : false,
integer: false,
});
};
exports._randomNumber = _randomNumber;
const scalar = (props) => {
if (props.minimum === props.maximum &&
(props.exclusiveMinimum || props.exclusiveMaximum))
throw new Error("Exclusive numeric range is empty.");
const value = Math.random() * (props.maximum - props.minimum) + props.minimum;
if ((props.exclusiveMinimum && value === props.minimum) ||
(props.exclusiveMaximum && value === props.maximum)) {
const middle = props.minimum + (props.maximum - props.minimum) / 2;
if (middle <= props.minimum || middle >= props.maximum)
throw new Error("Exclusive numeric range has no representable value.");
return middle;
}
return value;
};
const getLowerBoundary = (schema) => selectBoundary(schema.minimum === undefined
? null
: { value: schema.minimum, exclusive: false }, schema.exclusiveMinimum === undefined
? null
: { value: schema.exclusiveMinimum, exclusive: true }, Math.max);
const getUpperBoundary = (schema) => selectBoundary(schema.maximum === undefined
? null
: { value: schema.maximum, exclusive: false }, schema.exclusiveMaximum === undefined
? null
: { value: schema.exclusiveMaximum, exclusive: true }, Math.min);
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=_randomNumber.js.map