typia
Version:
Superfast runtime validators with only one line
54 lines (53 loc) • 1.79 kB
JavaScript
import { _randomInteger } from "../_randomInteger.mjs";
//#region src/internal/private/__randomComposition.ts
/**
* Splits `total` into `count` parts, each inside `[minimum, maximum]`.
*
* Used where a format's length is the sum of its segments — an IPv4 octet spans
* one to three digits, an IPv6 group one to four — so a requested total length
* is realized by choosing how many characters each segment contributes instead
* of redrawing whole addresses and hoping one lands in the window (issue
* #2284).
*
* The caller guarantees `count * minimum <= total <= count * maximum`; each
* part is drawn from the range that still leaves the remaining parts
* satisfiable.
*/
const __randomComposition = (props) => {
const parts = [];
let remaining = props.total;
for (let i = 0; i < props.count; ++i) {
const rest = props.count - i - 1;
const value = _randomInteger({
type: "integer",
minimum: Math.max(props.minimum, remaining - rest * props.maximum),
maximum: Math.min(props.maximum, remaining - rest * props.minimum)
});
parts.push(value);
remaining -= value;
}
return parts;
};
/** Draws `length` decimal digits, leading zeros included. */
const __randomDigits = (length) => {
let text = "";
for (let i = 0; i < length; ++i) text += String(_randomInteger({
type: "integer",
minimum: 0,
maximum: 9
}));
return text;
};
/** Draws a decimal number of exactly `length` digits without a leading zero. */
const __randomNumeric = (length) => length <= 1 ? String(_randomInteger({
type: "integer",
minimum: 0,
maximum: 9
})) : String(_randomInteger({
type: "integer",
minimum: 1,
maximum: 9
})) + __randomDigits(length - 1);
//#endregion
export { __randomComposition, __randomDigits, __randomNumeric };
//# sourceMappingURL=__randomComposition.mjs.map