Lambda vs. function

Breton Slivka zen at zenpsycho.com
Mon Oct 27 14:34:24 PDT 2008


I don't know if anyone will find this relevant or useful, but in my
personal code, I have changed over to completely avoiding the switch
statement altogether, in favor of primarily using objects with
subscript notation.

instead of

switch(type) {
   case "big":
       //do something big
     break;
   case "small"
       //do something small
      break;
}

I would instead

var cases = {
   big: function (arg) { /* do something big */ },
   small: function (arg) { /* do something small */ }
}

var result = (cases[type] ? cases[type](something):"default result";

or, if each case has a lot of repeating code, I simply make an object
factoring out the parameters that are different, and use the case as a
look up for parameters, and feed them into the boiler plate code once.

The result can be a little less readable unfortunately, but I find
it's a bit tidier and succinct- and can also be much more readable if
I manage to do it right. Plus, it completely avoids the fall through
problem by making it impossible. Tail position might be a bit more
clear with this approach as well.


More information about the Es-discuss mailing list