2 ms·
switch (Math.floor(version)) { case 1: return 'result_1'; case 2: return 'result_2'; case 3: return 'result_3'; default:
by alerighi 6y ago
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?
- aastronaut 6y agoI think I didn't make my point quite clear. Let's consider the case where version 3.1 needs to return something different than version 3. 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"; // ... }