A JavaScript Function Map

I spent my morning fixed problems with JavaScript. By “problems” I mean “fixing code that three or four iterations of developers have been too lazy to do correctly.” Here is simplified version of a particularly stupidly-written function that I uncovered:

function addItem(f,addtype) {
if (addtype="ab") {
f.hideme.value='';
functName1();    }
if (addtype="bc") {
f.hideme.value='';
functName2();    } if (addtype="cd") {       f.hideme.value='';           functName3();     }
if (addtype="de") {          f.hideme.value='';      functName4();     }
if (addtype="ef") {
f.hideme.value='';
functName5();     }}

This seems to call for a switch statement, but I’ve never been a fan of switch statements in any language. I understand them, but I’ve found them to be a weird and fragile construct. I instead implemented a function map. That trick works like a charm in Python and I wondered if it worked in JavaScript. And it does — like charm:

function addItem(f,addType) {
f.hideme.value='';
var typeFunctions = {"ab": functName1,
"bc": functName2,
"cd": functName3,
"de": functName4,
"ef": functName5};
if (typeFunctions.hasObjectProperty(addType)) {
typeFunctions[addType]();
}
}

This works because functions in JavaScript are objects like everything else. Note, though, that in my construction of typeFunctions that I didn’t put in a () after each function. That is because I wanted the function object, not the return value of each function. That would have executed each function in the constructor! That was not what I wanted to do. The hasObjectProperty method makes sure that the value in addType is really a property name in typeFunctions. You can also easily more type/function pairs by simply adding them to the typeFunctions constructor.

Powered by ScribeFire.

2 Responses to “A JavaScript Function Map”

  1. Nubi Says:

    In the digital equivalent of ‘clean me’ written in the dirt on your dad’s truck…

    Update me!

  2. Where Are The Wise Men? » Blog Archive » The Busyness Around Us Says:

    [...] My loyal reader is restless (although he refuses  to update his own blog)  but, as always,  if I’m not busy blogging it must mean I’m busy elsewhere.  And it’s true now: [...]

Leave a Reply

You must be logged in to post a comment.