typia
Version:
Superfast runtime validators with only one line
33 lines • 1.53 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports._randomPattern = void 0;
const randexp_1 = __importDefault(require("randexp"));
const _randomPattern = (regex, props) => {
const r = new randexp_1.default(regex);
const min = props === null || props === void 0 ? void 0 : props.minLength;
const max = props === null || props === void 0 ? void 0 : props.maxLength;
// RandExp expands an unbounded quantifier to `randInt(token.min, token.min +
// r.max)`, so steering `r.max` biases the generated length toward the window.
// There is no matching floor control, so the length is still verified below.
if (max !== undefined)
r.max = max;
else if (min !== undefined && min * 2 > r.max)
r.max = min * 2;
const bounded = min !== undefined || max !== undefined;
const limit = bounded ? 1024 : 10;
for (let i = 0; i < limit; ++i) {
const str = r.gen();
if (regex.test(str) &&
(min === undefined || str.length >= min) &&
(max === undefined || str.length <= max))
return str;
}
throw new Error(bounded
? "unable to generate a random string matching the pattern within the length range."
: "unable to generate a random string matching the pattern.");
};
exports._randomPattern = _randomPattern;
//# sourceMappingURL=_randomPattern.js.map