I need to dynamically add cases to a switch. I want the user to be able to add items and every item needs it's own switch case.
You can use objects with callback functions instead:
//You can have initial cases
var callbacks = {
'something': [() => 42]
};
// and you can create a 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 entries using:
add('something', function() {
// case for something
});
NOTE:
You can also modify this to work a little bit differently 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 for 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 a key in an array.