class CL {
constructor(conditions) {
this._conditions = conditions;
}
toString() {
this._depth = 0;
this._index = 0;
this._curr = this._conditions[0];
if (!this._curr) return null;
var r = new Where();
this._join(r);
return r.toString();
}
_join(r) {
if (Math.abs(this._curr.depth) == this._depth) {
this._join2(r, this._curr);
this._index++;
if (this._index < this._conditions.length) {
var t = this._curr.depth;
this._curr = this._conditions[this._index];
if (t < 0) {
this._depth--;
return;
}
return this._join(r);
} else return this._curr = null;
}
if (this._curr.depth >= 0) {
if (this._depth < this._curr.depth) {
var w = new Where();
var type = this._curr.type;
this._depth++;
this._join(w);
if (!w.isEmpty()) this._join2(r, { expression: w, type: type });
if (this._curr == null) return;
var t = Math.abs(this._curr.depth);
if (t < this._depth) return this._depth--;
else return this._join(r);
}
else return this._depth--;
}
else {
var t = this._curr.depth * -1;
if (t > this._depth) throw `此处depth绝对值应小于等于前一个条件对应的绝对值,${this._index}`;
return this._depth--;
}
}
_join2(a, b) {
a[b.type == 1 ? "and" : "or"](b.expression);
}
}
class Where {
and(exp) {
this._join(exp, "&&");
}
or(exp) {
this._join(exp, "||");
}
_join(exp, op) {
if (exp instanceof Where) exp = `(${exp.toString()})`;
this._exp = this._exp ? `${this._exp} ${op} ${exp}` : exp;
}
isEmpty() {
return !!!this._exp;
}
toString() {
return this._exp || "";
}
}
console.log(new CL([
{ type: 1, expression: "a==b", depth: 0 },
{ type: 1, expression: "b>0", depth: 2 },
{ type: 1, expression: "c", depth: -2 },
{ type: 2, expression: "d", depth: -1 },
{ type: 1, expression: "e", depth: 0 }
]).toString());
>> a==b && ((b>0 && c) || d) && e