switch (Math.floor(version)) {
case 1:
return 'result_1';
case 2:
return 'result_2';
case 3:
return 'result_3';
default:
throw new Error('...');
}
Isn't that more clear? switch (Math.floor(version)) {
case 1:
return 'result_1';
case 2:
return 'result_2';
case 3:
return 'result_3';
default:
throw new Error('...');
}
Isn't that more clear?A good (IMHO) early-return pattern would look like this:
if (version >= 3.1) {
return "result_3_1";
}
if (version >= 3) {
return "result_3";
}
// ...
...but in the wild I often see it developed into something like this: if (version >= 3) {
if (version === 3.1) {
return "result_3_1";
}
return "result_3";
}
// ...
...probably because people like to see major version numbers packaged together in blocks.With the switch-true on the other hand I could make good use of this 'stepping through ranges'-problem and could even make use of the fallthrough, in case it should fall back to a different value:
switch (true) {
case version >= 3.1:
return "result_3_1"; // just comment this out if you need the result of version 3 instead
case version >= 3:
return "result_3";
// ...
}