PDA

View Full Version : Best way to write a function-selector function



Pyth007
Aug 22nd, 2006, 04:31 PM
Basically I've got one function that will change a "progress" symbol before some text (makes a <span>, adds some attributes and the unicode char. for the type of progress, and replaces the old <span> with this new one) based upon one of the parameters. There are three other functions that actually create the <span>, and the main function will select which of these to use based on one of its args (hense I'm calling it a selector-function). I know of two approaches that should work, but I'd like to know which would be best performance-wise (or if there might be a better way than what I thought). Here are the 3 "make-<span>" functions:


function haltSymbol()
{
// Makes a red box with an 'x' thru it
var symbol = document.createElement('span');
symbol.style.color="#F00";
symbol.style.fontSize="200%";
symbol.style.verticalAlign="middle";
symbol.innerHTML="\u2612";
return symbol;
}

function goSymbol()
{
// Makes a green box with a check-mark in it
var symbol = document.createElement('span');
symbol.style.color="#060";
symbol.style.fontSize="200%";
symbol.style.verticalAlign="middle";
symbol.innerHTML="\u2611";
return symbol;
}

function readySymbol()
{
// Makes a yellow bow with a '+' in it
var symbol = document.createElement('span');
symbol.style.color="#FD0";
symbol.style.fontSize="250%";
symbol.style.verticalAlign="-25%";
symbol.innerHTML="\u229E";
return symbol;
}


One possibility for the selector would be to use eval, since all of the function names are similar:



function changeProgress(obj, act)
{
obj.replaceChild(eval(act+"Symbol()"), obj.getElementsByTagName('span')[0]);
}


However, eval is considered slow, so I was toying around with the idea of just using a switch on the 'act' arg (perhaps numeric instead of string) that just calls three separate replaceChild functions with the correct Symbol() function as its first arg.

But I'm not sure if the switch would actually be faster than the eval, or if there was some other way of doing this....

vwphillips
Aug 22nd, 2006, 04:58 PM
obj.replaceChild(window[act+'Symbol'](),obj.getElementsByTagName('span')[0]);

Pyth007
Aug 24th, 2006, 07:21 PM
Thanx... I wasn't sure if functions could be called with bracket notation... And I kept wanting to use 'document' for the scope instead of 'window' even though I knew that the function wasn't a part of the html document...