@thinman/ts-factory
Version:
TypeScript factories for generating fixtures, with custom constructor support. No docs yet, sorry.
28 lines (26 loc) • 1.41 kB
JavaScript
class ClassFactory {
constructor(clazz, constructorParameterFn, attributeCreatorFn) {
this.parseFnOrValue = (val, fallbackValue) => {
if (typeof val === "function") {
return val();
}
return (val !== null && val !== void 0 ? val : (fallbackValue ? this.parseFnOrValue(fallbackValue) : undefined));
};
this.generate = (attributeOverrides) => {
let newInstance = new this.clazz(...this.parseFnOrValue(this.constructorParams, []));
return Object.assign(newInstance, this.parseFnOrValue(this.extraAttributes, {}), this.parseFnOrValue(attributeOverrides, {}));
};
this.generateMany = (howMany, attributeOverrides) => {
const arr = Array(howMany).fill(undefined);
return arr.map(() => this.generate(attributeOverrides));
};
this.extend = (options) => {
const { constructorParams, extraAttributes } = options;
return new ClassFactory(this.clazz, () => this.parseFnOrValue(constructorParams, this.constructorParams), () => Object.assign(this.parseFnOrValue(this.extraAttributes, {}), this.parseFnOrValue(extraAttributes, {})));
};
this.extraAttributes = attributeCreatorFn;
this.constructorParams = constructorParameterFn;
this.clazz = clazz;
}
}
export { ClassFactory };