javascriptswitch-statement

Is there a clever way/trick to reuse a switch statement that does different things in the cases?


I use the same switch statement over and over, but the functionality in each case my differ.

switch(type){
  case "t1": 
    fnA();
    break;  
  case "t2": 
    fnB();
    break;
  ...
}

switch(type){
  case "t1": 
    fnZ();
    break;  
  case "t2": 
    fnY();
    break;
  ...
}

I don't know if there's a better or more clever way to do this. I couldn't think of anything, so I thought I'd toss it to you fine folks. Thanks in advance.

EDIT: to make more sense of it, think of it like this: in the first switch, depending on the type, data will be inserted added to an object a certain way. In the second switch, data will be deleted from an object a certain way.


Solution

  • I think this looks like a good situation to use object-oriented programming.

    1. Create a class for each type
    2. Whenever you need to do something which is doing something differently depending on the type, call type.someFunction(). Make each type class implement this function differently.