pragmatic-fp-ts
Version:
Opinionated functional programming library with easy use in mind
37 lines (36 loc) • 1.25 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.defmethod = exports.defmulti = exports.MultiMethod = void 0;
class MultiMethod extends Function {
constructor(dispatch) {
super();
const methods = {};
const multi = function (...args) {
const dispatchKey = dispatch(...args);
const method = methods[dispatchKey] || methods.default;
if (!method) {
throw new Error(`No method implementation for dispatch key ${dispatchKey}`);
}
return method(...args);
};
multi.defmethod = (dispatchKey, method) => {
if (methods[dispatchKey]) {
console.warn(`Overriding definition of ${dispatchKey}`);
}
methods[dispatchKey] = method;
};
return multi;
}
}
exports.MultiMethod = MultiMethod;
function defmulti(dispatch) {
return new MultiMethod(dispatch);
}
exports.defmulti = defmulti;
function defmethod(multimethod, dispatchResult, impl) {
if (!multimethod.defmethod) {
throw new Error(`Can not extend given method: not a multi method`);
}
multimethod.defmethod(dispatchResult, impl);
}
exports.defmethod = defmethod;