开发者

Most elegant way to make this javascript code DRY

Here is a snippet of my JavaScript Code that I want to DRY up:

if(开发者_运维问答agency == 'abcd')map.entities.push(abcd);
if(agency == 'efgh')map.entities.push(efgh);
if(agency == 'xyz')map.entities.push(xyz);
if(agency == 'pqrs') map.entities.push(pqrs);
if(agency == 'values')map.entities.push(values);

Now in future may have more ifs for different keys coming in. JavaScript doesnt offer a build in HashMap which i can use here. And using arrays and id stuff to make it DRY is too tacky. Is there a more simpler solution to this? May be something like this

if(agency == 'abcd')map.entities.push(stringToVariable('abcd'));

then I can just use a for and iterate through the keys. I am not sure though this possible at all in JavaScript.


Well maybe:

map.entities.push({abcd: abcd, efgh: efgh, xyz: xyz}[agency]);

To me, this is a situation that calls for stepping back and re-thinking more of the situation, as it's just inherently ugly as it stands. Why are there all these separate variables, instead of a single object with keys corresponding to "agency" values?


There's a legitimate case for using eval here as long as you know agency values are clean:

map.entities.push(eval(agency));


Every object in javascript IS a hashmap (at least sort of a hashmap), that's why this code returns true:

var obj = {};
obj.test = "someVarVal";
obj.test === obj['test'];

So, what you can do is build up an object of returnvalues/functions like so:

var returns = {};
returns['abcd'] = function() {return 'abcd';};
returns['efgh'] = function() {return 'efgh';};

And then do

map.entities.push(returns[agency]());

If all your variables are statics you can do it even simpler, like so:

var returns = {};
returns['abcd'] = 'abcd';
map.entities.push(returns[agency]);


function _inArr(arr,itm)
{
  for (var i=0; i < arr.length; i++)
  {
     if (arr[i] == itm) return true;
  }
  return false;
}

var allowedAgencies = array['abcd','efgh','xyz','pqrs','values'];
if (_inArr(allowedAgencies, agency))
{
  map.entities.push(window[agency]);
}

The _inArr function is available in every major javascript package ($.inArray, for example).

I think the point is that JavaScript is a big hashmap. A global function name, for instance, is just a key into the window object. The same goes for any namespaced items.


var agency='foo',
    wanted_words=new Regexp(/^abcd|efgh|xyz|pqrs|values$/);

agency.match(wanted_words) && map.entities.push(eval(agency));

Assumes all possible values of agency exist as variables.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜