custom_string_patterns
Version:
Generate random and incrementing string patterns using regex and custom functions
220 lines (219 loc) • 13.1 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.patternGen = void 0;
var object_property_extractor_1 = __importDefault(require("object-property-extractor"));
var helpers_1 = require("./helpers");
var defaultIncrement = function (current, step) {
if (step === void 0) { step = 1; }
return Number(current) + step;
};
// Wrapper to returnn the defaultIncrement function with the step-size backed in
var getDefaultIncrementFn = function (step) { return function (current) {
return defaultIncrement(current, step);
}; };
function simpleCounter(init, increment) {
var count;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
count = init;
_a.label = 1;
case 1:
if (!true) return [3 /*break*/, 3];
return [4 /*yield*/, count];
case 2:
_a.sent();
count = increment(count);
return [3 /*break*/, 1];
case 3: return [2 /*return*/];
}
});
}
// A "short-hand" function if only one generated string is required
var patternGen = function (pattern, options, args) {
if (options === void 0) { options = {}; }
if (args === void 0) { args = {}; }
var pg = new PatternGenerator(pattern, options);
return pg.gen(args);
};
exports.patternGen = patternGen;
var PatternGenerator = /** @class */ (function () {
function PatternGenerator(pattern, _a) {
var _b = _a === void 0 ? {} : _a, getCounter = _b.getCounter, setCounter = _b.setCounter, _c = _b.counterInit, counterInit = _c === void 0 ? 1 : _c, _d = _b.incrementStep, incrementStep = _d === void 0 ? 1 : _d, _e = _b.incrementFunction, incrementFunction = _e === void 0 ? getDefaultIncrementFn(incrementStep) : _e, _f = _b.customReplacers, customReplacers = _f === void 0 ? {} : _f, numberFormat = _b.numberFormat, fallbackString = _b.fallbackString, defaultRangeAdd = _b.defaultRangeAdd, defaultRangeSubtract = _b.defaultRangeSubtract, regexMax = _b.regexMax;
var _this = this;
this.simpleCounter = simpleCounter(counterInit, incrementFunction);
this.getCounter = getCounter !== null && getCounter !== void 0 ? getCounter : (function () { return _this.simpleCounter.next(); });
this.setCounter = setCounter !== null && setCounter !== void 0 ? setCounter : null;
this.pattern = pattern;
var _g = (0, helpers_1.processInputPattern)(pattern, {
defaultRangeAdd: defaultRangeAdd,
defaultRangeSubtract: defaultRangeSubtract,
regexMax: regexMax,
}), randexpObject = _g.randexpObject, substitionMap = _g.substitionMap, randexpPattern = _g.randexpPattern;
this.randexpObject = randexpObject;
this.substitutionMap = substitionMap;
this.randexpPattern = randexpPattern;
this.incrementFunction = incrementFunction;
this.internalCounter = counterInit;
this.numberFormat = numberFormat;
this.customReplacers = customReplacers;
this.fallbackString = fallbackString !== null && fallbackString !== void 0 ? fallbackString : '';
this.randexpOptions = { defaultRangeAdd: defaultRangeAdd, defaultRangeSubtract: defaultRangeSubtract, regexMax: regexMax };
}
PatternGenerator.prototype.setPattern = function (newPattern) {
var _a = (0, helpers_1.processInputPattern)(newPattern, {}), randexpObject = _a.randexpObject, substitionMap = _a.substitionMap, randexpPattern = _a.randexpPattern;
this.pattern = newPattern;
this.randexpObject = randexpObject;
this.substitutionMap = substitionMap;
this.randexpPattern = randexpPattern;
};
PatternGenerator.prototype.setOptions = function (_a) {
var getCounter = _a.getCounter, setCounter = _a.setCounter,
// counterIncrement,
// counterInit -- can't change,
customReplacers = _a.customReplacers, numberFormat = _a.numberFormat, fallbackString = _a.fallbackString, defaultRangeAdd = _a.defaultRangeAdd, defaultRangeSubtract = _a.defaultRangeSubtract, regexMax = _a.regexMax;
if (getCounter)
this.getCounter = getCounter;
if (setCounter)
this.setCounter = setCounter;
if (customReplacers)
this.customReplacers = customReplacers;
if (numberFormat)
this.numberFormat = numberFormat;
if (fallbackString)
this.fallbackString = fallbackString;
if (defaultRangeAdd)
this.randexpObject.defaultRange.add(defaultRangeAdd[0], defaultRangeAdd[1]);
if (defaultRangeSubtract)
this.randexpObject.defaultRange.subtract(defaultRangeSubtract[0], defaultRangeSubtract[1]);
if (regexMax)
this.randexpObject.max = regexMax;
};
// Generate new string
PatternGenerator.prototype.gen = function (args) {
var _a, _b;
if (args === void 0) { args = {}; }
return __awaiter(this, void 0, void 0, function () {
var _c, shouldIncrement, _d, customArgs, data, newCount, _e, _f, _g, generatedRandexString, captureGroupMatches, outputString, counters, functions, functionResultPromises, functionResults, dataProperties;
var _this = this;
return __generator(this, function (_h) {
switch (_h.label) {
case 0:
_c = args.shouldIncrement, shouldIncrement = _c === void 0 ? true : _c, _d = args.customArgs, customArgs = _d === void 0 ? {} : _d, data = args.data;
if (!shouldIncrement) return [3 /*break*/, 2];
_f = helpers_1.parseGeneratorOutput;
return [4 /*yield*/, this.getCounter()];
case 1:
_e = _f.apply(void 0, [_h.sent()]);
return [3 /*break*/, 3];
case 2:
_e = this.internalCounter;
_h.label = 3;
case 3:
newCount = _e;
this.internalCounter = newCount;
if (!this.setCounter) return [3 /*break*/, 6];
_g = this.setCounter;
return [4 /*yield*/, this.incrementFunction(newCount)];
case 4: return [4 /*yield*/, _g.apply(this, [_h.sent()])
// Create randexp string (with substitutions)
];
case 5:
_h.sent();
_h.label = 6;
case 6:
generatedRandexString = this.randexpObject.gen();
captureGroupMatches = (_b = (_a = generatedRandexString.match(new RegExp(this.randexpPattern))) === null || _a === void 0 ? void 0 : _a.slice(1)) !== null && _b !== void 0 ? _b : [];
outputString = generatedRandexString;
counters = Object.entries(this.substitutionMap).filter(function (c) { return c[1].type === 'counter'; });
counters.forEach(function (_a) {
var index = _a[0], counter = _a[1];
if ('length' in counter) {
var formattedCounter = (0, helpers_1.formatCounter)({
value: _this.internalCounter,
numberFormat: _this.numberFormat,
length: (counter === null || counter === void 0 ? void 0 : counter.length) || 0,
});
outputString = outputString.replace(new RegExp("<".concat(index, ">")), formattedCounter);
}
});
functions = Object.entries(this.substitutionMap).filter(function (f) { return f[1].type === 'function'; });
functionResultPromises = functions.map(function (_a) {
var _b;
var index = _a[0], f = _a[1];
if ('funcName' in f) {
var funcName = f === null || f === void 0 ? void 0 : f.funcName;
var args_1 = (0, helpers_1.getArgs)(funcName, f === null || f === void 0 ? void 0 : f.args, customArgs, captureGroupMatches, data);
if (!funcName)
throw new Error('Missing Function name');
return (_b = _this.customReplacers)[funcName].apply(_b, args_1);
}
});
return [4 /*yield*/, Promise.all(functionResultPromises)]; // for async functions
case 7:
functionResults = _h.sent() // for async functions
;
functions.forEach(function (_a, i) {
var index = _a[0], _ = _a[1];
outputString = outputString.replace(new RegExp("<".concat(index, ">")), functionResults[i]);
});
// Extract data properties
if (data) {
dataProperties = Object.entries(this.substitutionMap).filter(function (f) { return f[1].type === 'data'; });
dataProperties.forEach(function (_a) {
var index = _a[0], propertyObj = _a[1];
if ('property' in propertyObj) {
var property = propertyObj.property;
outputString = outputString.replace(new RegExp("<".concat(index, ">")), (0, object_property_extractor_1.default)(data, property, _this.fallbackString));
}
});
}
return [2 /*return*/, outputString
.replace(new RegExp(helpers_1.ESCAPED_OPEN_ANGLE_BRACKET, 'g'), '<')
.replace(new RegExp(helpers_1.ESCAPED_CLOSE_ANGLE_BRACKET, 'g'), '>')];
}
});
});
};
return PatternGenerator;
}());
exports.default = PatternGenerator;