开发者

Is there a better way to write this javascript?

Is there a better way to write this JavaScript?

switch (l) {
    //A
    case '1-1-1':
    case '1-1-2':
    case '1-2-1':
    case '2-1-1':
    case '3-1-1':
        obj.result = 'A';
        break;
    //B
    case '1-2-2':
    case '1-2-3':
    case '2-2-2':
    case '2-2-3':
    case '3-2-2':
    case '3-3-1':
        obj.result = 'B';
        break;
    //C
    case '1-3-2':
    case '1-3-3':
    case '2-3-2':
    case '3-2-3':
        obj.result = 'C';
        break;
    //D
    case '3-3-2':
    case '3-3-3':
    开发者_运维技巧    obj.result = 'D';
        break;
    default:
        obj.result = 'AA';
        break;
}


The lookup table, as mentioned by Thilo in the comments:

var lookup =
{
    '1-1-1': 'A',
    '1-1-2': 'A',
    '1-2-1': 'A',
    '2-1-1': 'A',
    '3-1-1': 'A',

    '1-2-2': 'B',
    '1-2-3': 'B',
    '2-2-2': 'B',
    '2-2-3': 'B',
    '3-2-2': 'B',
    '3-3-1': 'B',

    '1-3-2': 'C',
    '1-3-3': 'C',
    '2-3-2': 'C',
    '3-2-3': 'C',
    '3-3-2': 'C',

    '3-3-3': 'D'
};

and its usage:

obj.result = lookup[l] || 'AA';

I can't say this is really any better than the switch version.


If you told us how you got those values, we might be able to come up with a more concise solution, but here's how you'd use a lookup table (generated kind of backwards):

var byResult={
    A: ['1-1-1', '1-1-2', /* ... */],
    B: ['1-2-2', '1-2-3', /* ... */],
    /* ... */
};
var byInput={};
for(var output in byResult) {
    if(!Object.prototype.hasOwnProperty.call(byResult, output)) {
        continue;
    }
    var inputs=byResult[output];
    for(var i=0, l=inputs.length; i<l; i++) {
        var input=inputs[i];
        byInput[input]=output;
    }
}
function lookup(value) {
    if(Object.prototype.hasOwnProperty.call(byInput, value)) {
        return byInput[value];
    }else{
        return 'AA';
    }
}


Encapsulate the number to letter processing in a function so that your main code doesn't need to know how the translation is done. Call it like this:

obj.result = getThing(l);

// or, given your comment that l is formed by concatenating three
// values you could do the concatenation in the function
obj.result = getThing(v1, v2, v3);

Then within getThing() you can use your existing switch statement, or the lookup table from Matt Ball's answer, or whatever other method you like. And you can change the method at any time with no impact on the code that calls the function.

function getThing(v1, v2, v3) {
   var l = v1 + "-" + v2 + "-" + v3;
   // use lookup, switch, whatever
   return "somecode";
}

Note: don't actually call your function "getThing"; replace "Thing" with something that describes whatever these letter codes really are.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜