Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to the "switch" Statement

Tags:

I do not want to use Switch in my code, so I'm looking for some alternative

Example with Switch:

function write(what) {    switch(what) {      case 'Blue':       alert ('Blue');     break;      ...      case 'Red':       alert ('Red');     break;    }  } 

Example without Switch:

colors = [];  colors['Blue'] = function() { alert('Blue'); }; colors['Red'] = function() { alert('Red'); };   function write(what) {    colors[what]();  } 

My questions are:

  1. Do you know any other alternatives?
  2. Is this best solution?
like image 992
Bambert Avatar asked Feb 21 '10 19:02

Bambert


People also ask

What can be used as an alternative to switch in C language?

Object oriented programming (OOP), that is virtual functions, are a substitute for switch .

What is the alternative of switch statement in python?

What is the replacement of Switch Case in Python? Unlike every other programming language we have used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping.

What is alternative of switch case in Java?

char, byte, short can be used in switches too.

What can be use instead of switch case in C++?

In this case, you could also use std::array<int, 5> , which, unlike std::vector<int> , can be constexpr .


1 Answers

I have only a note about your second approach, you shouldn't use an Array to store non-numeric indexes (that you would call in other languages an associative array).

You should use a simple Object.

Also, you might want to check if the what argument passed to your write function exists as a property of your colors object and see if it's a function, so you can invoke it without having run-time errors:

var colors = {};  colors['Blue'] = function() { alert('Blue'); }; colors['Red'] = function() { alert('Red'); };   function write(what) {   if (typeof colors[what] == 'function') {     colors[what]();     return;   }   // not a function, default case   // ... } 
like image 162
Christian C. Salvadó Avatar answered Oct 20 '22 09:10

Christian C. Salvadó