ts-randomizer
Version:
A tool to create random data by type parameters
102 lines • 3.6 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpecimenFactory = void 0;
const fp_1 = require("lodash/fp");
const types_1 = require("../types");
const util_1 = require("./util");
/**
* Creates anonymous variables by description of T.
*/
class SpecimenFactory {
input;
mutators = [];
arrayValueCount = 5;
/**
* @param input The description of type to create.
*/
constructor(input) {
this.input = input;
}
/**
* Creates an variable of the requested type.
* @returns An anonymous variable of type T.
*/
create() {
return this.mutators.reduce((out, mutator) => (mutator(out), out), this.generate());
}
/**
* Creates many anonymous objects.
* @returns A sequence of anonymous object of type T.
*/
createMany(minCount, maxCount) {
return (0, fp_1.range)(minCount || 0, maxCount || 0).map(() => this.create());
}
/**
* Registers that a writable property or field should be assigned an anonymous value
* as part of specimen post-processing.
* @param func An expression that identifies the property or field that will should have a value assigned.
*/
with(func) {
this.mutators.push(func);
return this;
}
generate() {
if (this.input === types_1.PropertyType.Undefined) {
return undefined;
}
if (this.input === types_1.PropertyType.Null) {
return null;
}
if ((0, fp_1.isString)(this.input)) {
return this.generateValue(this.input);
}
if ((0, fp_1.isArray)(this.input)) {
return this.generatePropertiesValues(this.input);
}
return this.generatePropertyValue(this.input);
}
generatePropertyValue(prop) {
if (prop.flag === types_1.DescriptionFlag.Array) {
return new SpecimenFactory(prop.description).createMany(this.arrayValueCount);
}
if (prop.flag === types_1.DescriptionFlag.Tuple) {
return prop.description.map(desc => new SpecimenFactory(desc).create());
}
if (prop.flag === types_1.DescriptionFlag.Method) {
return (() => new SpecimenFactory(prop.description).create());
}
if (prop.flag === types_1.DescriptionFlag.Enum && prop.possibleValues) {
return (0, fp_1.sample)(prop.possibleValues);
}
return new SpecimenFactory(prop.description).create();
}
generatePropertiesValues(props) {
return props.reduce((output, prop) => {
if (!prop || !prop.key) {
return output;
}
output[prop.key] = this.generatePropertyValue(prop);
return output;
}, {});
}
generateValue(type) {
switch (type) {
case types_1.PropertyType.String:
return (0, util_1.createString)();
case types_1.PropertyType.Number:
return (0, util_1.createNumber)();
case types_1.PropertyType.Boolean:
return (0, util_1.createBoolean)();
case types_1.PropertyType.Function:
return (0, util_1.createFunction)();
case types_1.PropertyType.Date:
return (0, util_1.createDate)();
case types_1.PropertyType.Object:
return (0, util_1.createObject)();
default:
return (0, util_1.createUnknown)();
}
}
}
exports.SpecimenFactory = SpecimenFactory;
//# sourceMappingURL=specimen-factory.js.map