JSFiddle - React, Tailwind, and code Playground

JavaScript

/* ajax333221 - https://github.com/ajax333221/Ternary-Optimizer */

var i, j, str, temp, preferAdvancedWhenEqual;

preferAdvancedWhenEqual = false; //e.g prefer (2*x+1) over (x?3:1)

str = "<table border='1'>";

for (i = -6; i < 6; i++) {
    str += "<tr>";

    for (j = -6; j < 6; j++) {
        temp = ternaryOptimizer(i, j, preferAdvancedWhenEqual);

        str += "<td title='same as ( x ? " + i + " : " + j + " )' style='background:#" + (~temp.indexOf("?") ? "bca" : "beb") + ";'>" + temp + "</td>";
    }

    str += "</tr>";
}

str += "</table>";

document.body.innerHTML = ("<strong>(hover cursor to see their originals)</strong><pre>" + str + "</pre><br><a href='https://github.com/ajax333221/Ternary-Optimizer' style='font-size:13px;color:#b5b5b5;'>https://github.com/ajax333221/Ternary-Optimizer</a>");

function ternaryOptimizer(num1, num2, bol) {
    var old, notGr, temp, temp2, temp3, rtn;

    old = ("(x?" + num1 + ":" + num2 + ")");
    notGr = (num1 < num2);

    if (num1 == num2) {
        rtn = num1;
    } else if (Math.abs(num1 - num2) == 1) { //if 'num1' and 'num2' differ by 1 unit
        rtn = (notGr ? (num2 + "-x") : ("x+" + num2));
    } else {
        rtn = ((!num1 || (num2 && notGr) ? "!" : "") + "x*");

        if (notGr) {
            //swap 'num1' and 'num2'
            temp = num1;
            num1 = num2;
            num2 = temp;
        }

        if (num2) {
            if (!num1) {
                //swap 'num1' and 'num2'
                num1 = num2;
                num2 = 0;
            }

            rtn = ("(" + rtn + "" + (num1 - num2) + ")+" + num2);
        } else {
            rtn += ("" + num1);
        }
    }

    temp2 = ("(" + rtn + ")").replace(/\(0\-/g, "(-").replace(/\+0\)/g, ")").replace(/\+\-/g, "-").replace(/^\(+|\)+$/g, "");
    temp2 = ((temp2 == "x") ? "x*1" : temp2).split(")");
    temp3 = temp2[0].split("*");

    rtn = ("(" + (temp3.length > 1 ? (temp3[1] + "*") : "") + temp3[0] + (temp2[1] || "") + ")");

   ...