type-plus
Version:
Provides additional types for TypeScript.
56 lines • 1.55 kB
JavaScript
import { requiredDeep } from 'unpartial';
export function stub(stub) {
return stub;
}
function build(init) {
return builder(init).create();
}
/**
* Create a builder for a stub function of type T.
*
* The builder contains two methods:
*
* `.with()`: adds additional handler or partial stub.
* `.create()`: creates the final stub function.
*
* @example
* ```ts
* const b = stub.builder<{ a: number; b: string }>({ a: 1 }).with({ b: 'b' }).create()
* b({ a: 2 }) // { a: 2, b: 'b' }
* ```
*/
function builder(init) {
return builderInternal([init]);
}
function builderInternal(initializers) {
const builder = {
/**
* Adds an init object or handler to the builder.
*
* If `init` is an object, it will be merged with the stub object.
* If `init` is a function, it will be called with the stub object.
*
* @return {Builder<T>} The builder instance.
*/
with(init) {
return builderInternal([...initializers, init]);
},
/**
* Creates the resulting stub function.
*/
create() {
return (stub) => {
return initializers.reduce((acc, init) => {
if (typeof init === 'function') {
return init(acc);
}
return requiredDeep(init, acc);
}, stub);
};
}
};
return builder;
}
stub.build = build;
stub.builder = builder;
//# sourceMappingURL=stub.js.map