by rovolo · 7y ago · 0 comments
How often do you use a 'switch' statement whose cases don't always end in 'return' or 'break'? The "coroutines in C" [0] article is a clever use of switch-case as a goto, but it seems like you need to invent new types of control flow to use 'goto' properly. Does anyone have other clever uses of 'switch'?
[0] https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
https://github.com/ricardobeat/require-tree/blob/master/inde...
The goal is to accept a 'filter' argument that can either be a string, an array of strings, a regular expression, or a filter function. It fully uses fall-through and the multiple entry points. I find it magical, in that it turns all of those into a function so the remainder of the code doesn't have to care, and it's not any less efficient. Similar feeling to finding a use case for 'Infinity' :)
switch (type(filter)) {
case 'array' : filter = filter.join('|')
case 'string' : filter = new RegExp('^('+filter.replace('*', '.*')+')$', 'i')
case 'regexp' : filter = filter.exec.bind(filter)
case 'function' : return filter
}Switch statements are much easier to maintain if you keep them one or two lines long, and just have it immediately delegate to a function call then break. I think that's true for almost any code-flow syntax: if/elseif/else blocks, various loops. They all break down quickly if you have too much in them.
I do, occasionally. I prefer the inverted golang switch where fallthrough needs to be specified, since these cases (heh) are generally the minority.