Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 659
It worked yesterday. Avatar asked Mar 23 '26 06:03

It worked yesterday.


2 Answers

You could use a switch statement but more complex logic such as && starts to get more complicated (they are really designed for just quick one to one comparisons). I would stick with what you have if you want that more complex logic. It is technically the slowest but if all the other ways are very complicated to implement the gain in performance will not be worth it.

like image 134
carloabelli Avatar answered Mar 24 '26 18:03

carloabelli


you can use switch statements http://www.w3schools.com/js/js_switch.asp

like image 36
Anit K Avatar answered Mar 24 '26 18:03

Anit K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!