Dynamically adding cases to a switch

You can use object with callback functions instead:

// you can have initial casses
var callbacks = {
   'something': [() => 42]
};

// and you can create new entry with this function
function add(_case, fn) {
   callbacks[_case] = callbacks[_case] || [];
   callbacks[_case].push(fn);
}

// this function work like switch(value)
// to make the name shorter you can name it `cond` (like in scheme)
function pseudoSwitch(value) {
   if (callbacks[value]) {
      callbacks[value].forEach(function(fn) {
          fn();
      });
   }
}

and you can add new entry using:

add('something', function() {
   // case for something
});

NOTE:

You can also modify this to work a little bit different than the original switch because you can have a function that returns a value and use a switch-like expression (like in Scheme where everything is an expression that returns a value):

const value = cond(42);

Writing this type of pseudoSwitch/cond function is left as an exercise to the reader.

NOTE 2:

By default objects in JavaScript use strings as keys and if you need to use something that can’t be easily converted to a string, like objects (that will be converted to [Object object]) then you can use Map object that accepts anything as keys. Note that symbols work differently and they are not converted to a string when used as key in array.

Leave a Comment