Re:Math.min(Math.max(num, min), max)
by yesbabyyes on Thursday August 20, 2020 @10:57AM
(#24223944)
Good point, for those who need to implement a slick compareFunction for numbers, Math.sign is great:
[min, num, max].sort((a, b) => Math.sign(a - b))[1]
An entirely different alternative is poor man's match: switch (true) {
case num > max: return max;
case num < min: return min;
default: return num;
}Why sign though? I always write my sorts like this.
.sort((a, b) => a - b)Is there a better way to grab a reference to the subtraction operator?
I assume you're referring to a point-free reference.
Only by defining a `const subtract = (a, b) => a - b;`, which isn't really point-free.
Or by using a different language.
Wait, really? I just had to double-check my one JS project for bugs and either I used to know this gotcha or I got lucky. My sort()-ing needed to handle NaNs carefully so I was already using custom comparators.
Re:Math.min(Math.max(num, min), max)
by TimTheTinker on Thursday August 20, 2020 @01:18PM
(#24225767)
"lexicographically" is a better descriptor than "alphabetically", since it's sorting by UTF-8 code point value.
Re:Math.min(Math.max(num, min), max)
by edflsafoiewq on Thursday August 20, 2020 @02:01PM
(#24226341)
It sorts by UTF-16 code unit.
Re:Math.min(Math.max(num, min), max)
by TimTheTinker on Thursday August 20, 2020 @02:34PM
(#24226808)
Of course, my bad.
Very good point. I thought of it more as pseudocode.
imho a very elegant solution and probably works in most languages, I was surprised by JavaScript's behaviour myself
For a real fun headscratcher consider
[ '9', '10', '11', '12', '13' ].map(parseInt)
Thank you for this exercise! I figured it out!
[ROT 13] spoiler: cnefrVag frpbaq nethzrag vf onfr, znc frpbaq nethzrag vf vaqrk va neenl. 10 vf gur frpbaq nethzrag, vaqrk 1. cnefrVag(10, 1) unf vyyrtny onfr
https://stackoverflow.com/questions/21019902/why-cant-javasc...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...