Alternative to a million IF statements

A switch statement, as your code is only if-elses 🙂

No, honestly. The best thing would be if you’d find a simple algorithm to create an email address from any given name, like

function mail(name) {
    return name.toLowerCase() + "@gmail.com";
}
var email = mail("Bob") // example usage

If they differ to much, you might use an object as a key-value-map:

var mails = {
    "Steve": "[email protected]",
    "Bob": "[email protected]",
    ...
}
var email = mails[name];

You could also combine those, if you have to determine which algorithm you need to use:

var map = [{
    algorithm: function(name) { return name+"@something"; },
    names: ["Steve", "Bob", ...]
},{
    algorithm: function(name) { return "info@"+name+".org"; },
    names: ["Mark", ...]
}];
for (var i=0; i<map.length; i++)
    if (map[i].names.indexOf(name) > -1) {
        var email = map[i].algorithm(name);
        break;
    }

or when it is a bit simpler:

var domains = {
    "gmail.com": ["Steve", "Bob", ...],
    "free.xxx": ["Mark", ...],
    ...
};
for (var domain in domains)
    if (domains[domain].indexOf(name) > -1)
        var email = name.toLowerCase()+"@"+domain;
        break;
    }

Just try to reduce the amount of data to deliver to the client as much as you can.

Leave a Comment