typia
Version:
Superfast runtime validators with only one line
59 lines (58 loc) • 2.24 kB
JavaScript
import { _randomMultiple } from "./_randomMultiple.mjs";
//#region src/internal/_randomNumber.ts
const _randomNumber = (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,
exclusiveMinimum: lower?.exclusive ?? false,
exclusiveMaximum: upper?.exclusive ?? false
}) : _randomMultiple({
minimum,
maximum,
multipleOf: schema.multipleOf,
exclusiveMinimum: lower?.exclusive ?? false,
exclusiveMaximum: upper?.exclusive ?? false,
integer: false
});
};
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 === void 0 ? null : {
value: schema.minimum,
exclusive: false
}, schema.exclusiveMinimum === void 0 ? null : {
value: schema.exclusiveMinimum,
exclusive: true
}, Math.max);
const getUpperBoundary = (schema) => selectBoundary(schema.maximum === void 0 ? null : {
value: schema.maximum,
exclusive: false
}, schema.exclusiveMaximum === void 0 ? 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;
};
//#endregion
export { _randomNumber };
//# sourceMappingURL=_randomNumber.mjs.map