UNPKG

cooky-cutter

Version:

Object factories for testing in TypeScript

43 lines (42 loc) 1.76 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.extend = void 0; const compute_1 = require("./compute"); const define_1 = require("./define"); /** * Define a new factory function from an existing factory. The return value is a * function that can be invoked as many times as needed to create a given type * of object. Use the config param to define how the object is generated on each * invocation. * * @param base An existing factory to extend. * @param config An object that defines how the factory should generate objects. * Each key can either be a static value, a function that receives the * invocation count as the only parameter or another factory. */ function extend(base, config) { let invocations = 0; const factory = (override = {}) => { invocations++; let result = base(override); // The computed keys starts empty (rather than including the base result // keys) because those values should get overridden and recomputed by the // extended values. let computedKeys = []; // TODO: this cast is necessary for the correct `key` typings and playing // nice with `compute`. Ideally, this can be avoided. const values = Object.assign({}, config, override); for (let key in values) { compute_1.compute(key, values, result, invocations, [], override, computedKeys); } return result; }; // Define a property to differentiate this function during the evaluation // phase when the factory is later invoked. factory.__cooky_cutter = define_1.FACTORY_FUNCTION_KEY; factory.resetSequence = () => { invocations = 0; }; return factory; } exports.extend = extend;