Search code examples
node.jspretty-print

pretty printing from any format to a desired format


I am wondering if there is a way by which I can convert a format, let's say a tree to a format I want. Take the following example:

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)


Solution

  • This is practically the algorithm that you are looking for, but please take note that this algorithm doesn't support the deep conditions.

    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`);