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

UPDATE

Another question

Could someone please explain me how to implement map based conditioning for this code


Source: oop

Leave a Reply