简体   繁体   中英

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;
}

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';
    }
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM