quick js tip

Instead of the following:

function getResult(el){
  switch(el.value){
    case '0': return func1();
    case '1': return func2();
    case '3': return func3();
    case '5': return func4();
  }
}

Do this:

function getResult(el){
  return [func1,func2,0,func3,0,func4][parseInt(el.value)]();
}

This assumes that the value will always match one of the valid functions.

1 Comments.

  1. I’d use the former over the latter – ease of readibility and maintainability (and holding on to my sanity) always wins out over obfuscated code.

%d bloggers like this: