chai-latte
Version:
Build expressive & readable fluent interface libraries.
93 lines • 3.38 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConfigurableCallback = void 0;
const getPrototypeChain_1 = require("./getPrototypeChain");
const getPrimitiveType_1 = require("./getPrimitiveType");
class ConfigurableCallback {
static list = new Set();
static configByCallback = new Map();
static configByProps = new Map();
static getBuilderOf(key) {
return this.configByCallback.get(key) || this.configByProps.get(key);
}
expression;
returnByArg = new Map();
props = {};
args = [];
execute;
constructor(expression) {
this.expression = expression;
this.execute = expression.callback;
this.args = expression.args ?? [];
ConfigurableCallback.list.add(this);
ConfigurableCallback.configByCallback.set(this.callback, this);
ConfigurableCallback.configByCallback.set(this.handleFunctionCall, this);
ConfigurableCallback.configByProps.set(this.props, this);
// console.log('ConfigurableCallback.configByCallback', ConfigurableCallback.configByCallback);
// (this.handleFunctionCall as any).aaaa = "AAAAAA"
}
lastArg = null;
updateReturn(obj) {
this.returnByArg.set(this.lastArg, obj);
this.lastArg = undefined;
}
updateArg(arg) {
this.lastArg = arg;
this.returnByArg.set(this.lastArg, this.execute);
}
callIndex;
setCallIdx(idx) {
this.callIndex = idx;
}
originCallbackByArg = new Map();
setArgOrigin(arg, callback) {
this.originCallbackByArg.set(arg, callback);
}
getMatchedReturn(arg) {
const isExactMatch = this.returnByArg.has(arg);
if (isExactMatch) {
return this.returnByArg.get(arg);
}
const primitiveType = (0, getPrimitiveType_1.getPrimitiveType)(arg);
const isMatchPrimitiveType = this.returnByArg.has(primitiveType);
if (isMatchPrimitiveType) {
return this.returnByArg.get(primitiveType);
}
const prototypeChain = (0, getPrototypeChain_1.getPrototypeChain)(arg);
for (const proto of prototypeChain) {
const isMatchPrototype = this.returnByArg.has(proto);
if (isMatchPrototype) {
return this.returnByArg.get(proto);
}
}
}
getArgs() {
return this.args;
}
handleFunctionCall = (arg) => {
const matchedReturn = this.getMatchedReturn(arg);
switch (typeof matchedReturn) {
case 'function':
const allArgs = [...this.getArgs(), arg];
// clears accumulation of arguments for future calls
this.getArgs().splice(0);
return matchedReturn(...allArgs);
case 'object':
this.getArgs().push(arg);
return matchedReturn;
default:
this.getArgs().splice(0);
throw new Error('Unsupported Argument');
}
};
callback = new Proxy(this.handleFunctionCall, {
get: (target, prop, receiver) => {
if (this.props[prop]) {
return this.props[prop];
}
return Reflect.get(target, prop, receiver);
},
});
}
exports.ConfigurableCallback = ConfigurableCallback;
//# sourceMappingURL=ConfigurableCallback.js.map