mercredi 29 mars 2017

Changing if else from static to dynamic in javascript

I have an if else condition where, if I upload a file, it will see for the 'code name' i.e, 'abc1' in the file name and compare it to a hard coded value and the returned value will then be compared to a ProductLine. Here I am doing a two way search. how to get rid of all these if elses and make it straight like if I upload a file compare it with productLine and then return it. Below is the code.

    var findProductLineByFilename = function(filename, productLines) {
    filename = filename.replace(/( |\-|\.|_)/g, '');
    var i;
    for (i in productLines) {
        productLine = productLines[i];

        // XXX: Hard-code names
        if (productLine.code_name === 'abc1') {
            if (filename.search(/(war1)|(w1)|(abc1)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc2') {
            if (filename.search(/(w2)|(abc2)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc3') {
            if (filename.search(/(w3)|(abc3)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc4') {
            if (filename.search(/(w4)|(abc4)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc5') {
            if (filename.search(/(w5)|(abc5)/) >= 0) {
                return productLine;
            }
        }
    }
    return null;
};

Aucun commentaire:

Enregistrer un commentaire