jeudi 23 juillet 2015

Javascript if else alternatives

I have following code

function MyFunc() {

    var add = function (props) {

      if (props.hasOwnProperty('a') && props.hasOwnProperty('b')) {
        return 'ab';
      } else if (props.hasOwnProperty('c')) {
        return 'c';
      } else if (props.hasOwnProperty('d')) {
        return 'd';
      } else {
        throw new Error("Doomed!!!");
      }

    };

    var div = function () {
        return "Hello from div";
    };

    var methods = {
        add: add,
        div: div
    };

    var funcCall = function (obj) {

        if (!obj) {
            throw new Error("no Objects are passed");
        }

        return methods[obj.fName](obj.props);
    };

    return {
        func: function (obj) {
            return funcCall(obj);
        }
    };

}

var lol = new MyFunc();

When lol.func({fName: 'add', props: {a: 'a', b: 'b'}}); is run it should return the correct response from add functions inner if else statements. But there can be more than 20 else if occurrences. My question is will this be a reason for bad performance, Is there any alternative approch for achieving this

DEMO

Aucun commentaire:

Enregistrer un commentaire