6 ms·
Interesting pattern, first time I saw this: switch (true) { case cellA > cellB: return 1; case cellA < cellB: return -1;
by Leace 7y ago
Interesting pattern, first time I saw this:
switch (true) {
case cellA > cellB: return 1;
case cellA < cellB: return -1;
case cellA === cellB: return 0;
}
Source: https://htmldom.dev/sort-a-table-by-clicking-its-headers https://htmldom.dev/sort-a-table-by-clicking-its-headers
- planb 7y agoI had to think for a sec to get this. And this already makes it worse than 3 if statements. Does anyone really find this more readable?
- robto 7y agoComing from a lisp I often wish other languages had `cond` so I don't have to nest if statements. This looks like a poor man's cond. So yes, I do find this more readable. It makes it clear that only one branch will get executed.
- foldr 7y agoThis would be equally clear if the author had just used a sequence of if statements with a 'return' in each one. (Note that Javascript's case has fallthrough, so you can't immediately conclude that only one branch of a case will be executed.)
- hombre_fatal 7y agoYou don't have to nest if-statements and I would say nested-if is wrong. You simply use else-if. It's a flat structure just like cond.
- TheRealPomax 7y agoyou mean two if statements. The last case is a default return.
- hacker_9 7y agoInteresting at first glance, but what is the performance of this? It looks like all cases would have to be evaluated before picking one, so even slower than an if-else-if.
- XCSme 7y agoIsn't it going to short-circuit with the return of the first truthy statement?
- foldr 7y agoThe expression immediately to the right of each 'case' keyword is evaluated before the resulting values are compared to true.
- deleted 7y ago[deleted]
- richgieg 7y agoIf that's the case, then wouldn't both "asdf" and "qwer" be printed to the console when executing the following code? function test() { switch (true) { case console.log('asdf') === undefined: return 1; case console.log('qwer') === undefined: return 2; } } test();
- foldr 7y agoHmm, I wrote some similar test code before writing my comment, but only included one 'case'. Indeed, you're right, they're evaluated only as needed.
- XCSme 7y agoI think you can just do: if (cellA > cellB) return 1; if (cellA < cellB) return -1; if (cellA === cellB) return 0; Why is the switch better? Or even (less explicit, but shorter code): if (cellA === cellB) return 0; return cellA > cellB ? 1 : -1;
- cfv 7y agoA switch is literally a series of chained ifs. In most languages ir takes the form of a series of If(Variable == $CaseValue){ Yield $CaseBody() } But in some languages, like js, nothing is preventing you from hacking it to do something different. EDIT: Just how petty, sheltered and dumb does a person have to be to downvote a statement of fact and then not leave a response to justify that? Grow up already.
- pythonaut_16 7y agoIn that case you're not really hacking it. If you think about what a switch does and how it works, it makes perfect sense. It's just a bit unusual to do it that way.
- cfv 7y agoIs it not though? By exploiting the conditions to evaluate to true == $CaseValue you're subverting the expectation that the choices all rely on a single variable, all the while breaking fallthrough and default.
- marcus_holmes 7y agopresumably downvoting JS not your post hehe
- deleted 7y ago[deleted]
- K0SM0S 7y ago'Hacking' doesn't even begin to cover it. How about we don't `break` like we should (!) and instead have fallthrough¹ cases that execute several cases— or more —on purpose²? Oh, switches. Always the horror. In networking they somehow replaced bridges, but it's the same thing (that was never confusing to anyone, obviously). In (my) programming, a switch so often turns out to be a nice dressing hiding some horror pattern. And that Nintendo thing... nice games but 720p 30fps? Really?? When I re-read / refactor, I've got this nagging phrase in my mind, whenever I see one: “Kill the switch! Death to switches!” To conclude this perfectly balanced and nuanced opinion (!): some switches find their place; but most don't, and never should. ____ 1: SO: Should fallthrough be “allowed”? I move that whatever congress runs your country should outlaw it! But exceptions can be made... https://stackoverflow.com/a/188506/5376417 https://stackoverflow.com/a/188506/5376417 2: Book: (NSFW // Programming horror // mutilated code in this example) https://eloquentjavascript.net/02_program_structure.html#h_jMKsa0SXdL https://eloquentjavascript.net/02_program_structure.html#h_j... (upvoted you, if only to balance the weird ones) (note: this comment is meant absurd. do not downvote yourself into a reading mistake, the tone is funny ;-) Vanilla Javascript is funny.
- smt88 7y agoYou're seeing it for the first time because it's a bad pattern. It's confusing to a reader who is expecting a typical switch use-case, and it has no performance benefit over a series of if statements. I don't know about V8, but a lot of compilers would have a harder time optimizing this because of the strange structure. For mature compilers and naive (i.e. not-yet-profiled) projects, it's better to write what you mean and let the compiler optimize it.
- marcus_holmes 7y agoGo does this too, and it's actually OK once you get used to it. The switch statement is still saying "it's one of these things"
- pvg 7y agoThat entire example in general reads more like a cautionary tale about coding yourself into overly-specific clunk in the service of staying 'vanilla'. The 'type' of things being sorted is hardcoded into the html of the table and the actual js code. The comparator function has specific logic just to handle ascending and descending sorts of that that particular table. This one 'simple' example is already more convoluted and brittle than it would be even if you 'reinvented' your own framework-like thing.
- robocat 7y agoThe modern code is: return cellA.localeCompare(cellB); Because cellA and cellB are always strings: const cellA = rowA.querySelectorAll('td')[index].innerHTML; If using a framework, you would generally have typed JSON data, which is better. For example, makes number columns sort correctly (example code above sorts ‘10’ before ‘9’). Dealing with cells of tables is one area where code optimisations are needed if you care about performance and have a large table. There are multiple obvious problems e.g. looping over calls to querySelectorAll. That switch(true) statement is not what I would expect from a more experienced developer. It is show-off code that looks cute and works, but the compromises are not worth it (statement order is not obvious, if you make a mistake and two cases are true then do you know which wins, it could easily deoptimise the JIT compiler because it is doing something uncommon, I would worry how debuggers and code compressors would handle more complex cases, and understandability is poor for new devs IMHO).