5 ms·
Stage 1 ECMAScript proposal to add Math.clamp (among others): https://github.com/rwaldron/proposal-math-extensions https://github.com/rwaldron/proposal-math-ext
by rewq4321 6y ago
Stage 1 ECMAScript proposal to add Math.clamp (among others): https://github.com/rwaldron/proposal-math-extensions https://github.com/rwaldron/proposal-math-extensions
But it looks dead: https://github.com/rwaldron/proposal-math-extensions/issues/16 https://github.com/rwaldron/proposal-math-extensions/issues/...
As someone mentioned in the thread, nested ternary is easier to interpret:
(a > max ? max : (a < min ? min : a))
- jaffathecake 6y agoI don't find this a whole lot easier to read to be honest. It seems like doing minification manually, when we have tools to do that for us. An if statement seems a lot clearer, and minifies well https://twitter.com/jaffathecake/status/1296423819238944768 https://twitter.com/jaffathecake/status/1296423819238944768
- balfirevic 6y agoIt's just a matter of what you're used to. Both of those are equally clear to me.
- macspoofing 6y agoTo each his own but I disagree. Nested ternary's are hard to read and understand, and modifying them (by future devs) is tricky and error prone.
- deleted 6y ago[deleted]
- Stratoscope 6y agoTrue, nested ternaries can be hard to follow. And the excessive parentheses promote this way of looking at it. OTOH I think chained ternaries can be simple and easy to understand. Yes, they are the exact same thing in this case, but getting rid of those nested parens really helps, at least for me. sarah180's example is a good illustration. I would change the order of the tests because it makes more sense to me to check the min before the max. I'd also make one minor formatting change, because I code in a proportional font and can't line things up in columns: a < min ? min : a > max ? max : a Maybe people think differently, but to me that is super easy to understand, and much better than the confusing Math.min/max stuff. I would also wrap the whole thing inside a function: function clamp( value, min, max ) { return( value < min ? min : value > max ? max : value ); } Now that it's inside a function, you could change the code to use if statements, or Math.min/max, or whatever suits your preferences.
- sarah180 6y agoAt the risk of starting a style debate, this may be easier to read if you write it like an if-else: a > max ? max : a < min ? min : a
- KMag 6y agoUnless, of course, your language "designer" has no idea why every other language uses right-associative ternary operators.
- bangonkeyboard 6y agoThis was a "fun" bug to track down in a PHP codebase.