omnimatch
Version:
TypeScript tagged-union utility knife
34 lines • 1.42 kB
JavaScript
;
// Copyright (c) Will Temple
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Delegate handling of an input to a function based on the value of a discriminant property.
*
* The value of the input's discriminant is used to index into the pattern to retrieve a
* function to handle the input.
*
* If no entry exists in the pattern for the discriminant of the input, then `undefined` is
* returned. If no `discriminant` is provided, then the string "kind" is used as the default
* discriminant.
*
* @param input a value with a type discriminated by the {@link discriminator}
* @param pattern a map from discriminator values to a delegate function to handle that value
* @param discriminant the property name to use as the discriminant (`"kind"` if not provided)
*/
function match(input, pattern, discriminant) {
const delegate = pattern[input[discriminant !== null && discriminant !== void 0 ? discriminant : "kind"]];
return delegate ? delegate(input) : undefined;
}
exports.match = match;
function factory(discriminant) {
const d = discriminant !== null && discriminant !== void 0 ? discriminant : "kind";
const maker = new Proxy({}, {
get(_, key) {
return (fields) => (Object.assign({ [d]: key }, fields));
},
});
return maker;
}
exports.factory = factory;
//# sourceMappingURL=index.js.map