条件拼接

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值