从任何格式到所需格式的漂亮打印

时间:2018-07-28 12:04:37

标签: node.js pretty-print

我想知道是否有一种方法可以转换格式,比如说将树转换为我想要的格式。请看以下示例:

a -> b, d
f - > c 
f-> v

I want to have this as an output:


a implies (b and d)
f implies (c or v)

1 个答案:

答案 0 :(得分:0)

这实际上是您正在寻找的算法,但是请注意,该算法不支持较深的条件。

function mathLogic(inputs) {

    var rows = inputs.split("\n");
    for (var i in rows)
        rows[i] = rows[i].replace(/\s/g, "");
    console.log("Rows: ", rows)
    var logics = {};
    for (var i in rows) {
        var row = rows[i];
        var rowSplit = row.split("->");
        var from = rowSplit[0];
        var to = rowSplit[1];
        var ands = to.split(",");
        if (!logics[from])
            logics[from] = [];
        logic = logics[from];
        logic.push(ands);
    }
    for (var i in logics) {
        var implyString = i + " implies ";
        var orLogic = logics[i];
        var ors = [];
        for (var j in orLogic) {
            var or = orLogic[j]
            if (or.length > 1)
                ors.push("(" + or.join(" and ") + ")");
            else
                ors.push(or.join(" and "));
        }
        if (ors.length > 1)
            implyString += "(" + ors.join(" or ") + ")";
        else
            implyString += ors.join(" or ");
        console.log(implyString);
    }
}

mathLogic(`a -> b, d
  f - > c 
  f-> v`);