3 ms·
> it takes me ages to convince myself this implementation is correct It would take them less time to convince themself if they switched min and num to put the
by ebg13 6y ago
> it takes me ages to convince myself this implementation is correct
It would take them less time to convince themself if they switched min and num to put the values in proper semantic order: min < num < max.
Math.min(Math.max(min, num), max)
- jaffathecake 6y agoI don't think so. Whereas an if statement is easy to read https://twitter.com/jaffathecake/status/1296423819238944768 https://twitter.com/jaffathecake/status/1296423819238944768
- bhaak 6y agoThat still leaves the order of Math.min and Math.max undecided and will probably not help much if you get easily confused by the visuals of this code. I never thought about it but of course there must be code tongue twisters (or more correctly, brain twisters). Thinking about it, I would probably go with a less confusing implementation. Terse code is hard to read and the compiler is likely clever enough to choose the best implementation anyway.
- hansvm 6y ago> and the compiler is likely clever enough to choose the best implementation anyway. Not in my experience. The compiler is likely to be able to do something decent to it, but it'll probably be different. Consider the following snippets. For unsigned integers they're all equivalent (and return the max of x and m), but gcc with a wide range of flags can't recognize them as identical. (x<m) * m + (x>=m) * x (x<m) * (m-x) + x x<m ? m : x
- bhaak 6y agoThere can always be things that trip the compiler. Without looking at the actual assembler, you never know that. Interestingly in your example, clang is able to resolve the first and the third line to the same assembler code. https://godbolt.org/z/navMEc https://godbolt.org/z/navMEc I do wonder why it then isn't able to do that for the second line. Possibly because the CPU might have different flags set after processing the substraction? But I'm not sure if your example is a good argument after I said I prefer less confusing code and you present an example which even confuses the compiler. ;-)