2013-12-19

JavaScript Name Hosting and One-Liner Functional Style

JavaScript has name hosting. 〔☛ JavaScript: Variable & Function Declaration Order: Name Hoisting〕 and i think Douglas Crockford recommends to move all vars to the top, to reflect reality.

but look at the following code. Moving all var to the top would be silly.

function displaySearchResult (charArray, anchorNode) {
    // clear the result first
    while (anchorNode.hasChildNodes()) {
        anchorNode.removeChild(anchorNode.lastChild);
    }

    if ( charArray.length === 0 && searchBox.value.length !== 0) {
        var noResult = document.createElement("span");
        noResult.innerHTML = "none found. Try type more characters, or try “star”, decimal search “#97”, hexadecimal search “#x61”, or enter a Unicode “♥”";
        noResult.style.color="red";
        anchorNode.appendChild(noResult);
    } else {

        for (var ii = 0; ii < charArray.length ; ii++) {

            var uNum = charArray[ii];
            var uHex = uNum.toString(16);
            var uChar = String.fromCodePoint(uNum);
            var uName = unicodedata[uNum];

            var resultItem = document.createElement("table");
            resultItem.innerHTML = "<tr><td><span style='font-size:6ex'>" + uChar + "</span></td><td>" + uNum + "<br />x" + uHex + "</td></tr><tr><td colspan='2'>" + htmlEncode(uName) + "</td></tr>";

            resultItem.style.display="inline-block";
            resultItem.style.border="solid thin red";
            resultItem.style.width="18ex";
            resultItem.style.margin="0.2ex";
            resultItem.style.padding="0.2ex";
            resultItem.style.borderRadius="14px";

            anchorNode.appendChild(resultItem);
        } }}

i think to solve this, one'd do heavy functional style instead. That is, often just eliminate variables all together.

For example, this block:

var uNum = charArray[ii];
var uHex = uNum.toString(16);
var uChar = String.fromCodePoint(uNum);
var uName = unicodedata[uNum];

var resultItem = document.createElement("table");
resultItem.innerHTML = "<tr><td><span style='font-size:6ex'>" + uChar + "</span></td><td>" + uNum + "<br />x" + uHex + "</td></tr><tr><td colspan='2'>" + htmlEncode(uName) + "</td></tr>";

would be rewritten as:

resultItem = document.createElement("table");
resultItem.innerHTML = (function(uChar, uNum, uHex, uName ){return "<tr><td><span style='font-size:6ex'>" + uChar + "</span></td><td>" + uNum + "<br />x" + uHex + "</td></tr><tr><td colspan='2'>" + htmlEncode(uName) + "</td></tr>"})( charArray[ii], uNum.toString(16), String.fromCodePoint(uNum), unicodedata[uNum] )

yep. I think that's what i'll do. How this reminds me my Mathematica code days. My Mathematica code is all like that.

g+ discussion https://plus.google.com/+XahLee/posts/776XQf46CvZ