Tuesday, July 10, 2012

Condencing Long If Statements Where A Value Is One of Many Values

Every once in a while I come across a situation where I need to run a section of code if it is one of many different values. There are a several solutions to this situation.

The most common is the basic long form statement. This is well and good but takes a while to write and is pretty verbose. In my opinion, it is actually a bit harder to read.
$('.format-number').each(function () {
    var t = $(this);
    if (t[0].nodeName === "INPUT" || t[0].nodeName === "SELECT") {
        t.val(SomeStringFormatFunc(t.val()));
    }
    else {
        t.text($.fn.autoNumeric.Format(t.attr('id'), t.text()));
    }
});
Let's focus on the if statement. After some reworking the statement, we can use an array and the indexOf function to determine the same. It is a little shorter.
if (["INPUT", "SELECT"].indexOf(t[0].nodeName) >= 0) {
The next example exploits some, sadly rarely used, JavaScript functionality and makes it shorter yet. Using an JSON object, dictionary look up, and if statement evaluation knowledge, the following uses all of these to achieve the same result.
if (({ "INPUT": 1, "SELECT": 1 })[t[0].nodeName]) {
A potential benefit of both refactor attempts is that the array and JSON object can be refactored if those need to be reused in other places. Alternatively, if it needs to be configurable, abstracting the array or JSON object solutions cater to that need.

No comments: