4 ms·
"JavaScript is horrible." > function byNum(a,b) {return +a>+b} undefined > [5, 10, 1].sort(byNum) [1, 5, 10] No, it's not.
by ceautery 13y ago
"JavaScript is horrible."
> function byNum(a,b) {return +a>+b}
undefined
> [5, 10, 1].sort(byNum)
[1, 5, 10]
No, it's not.
- Morgawr 13y agothat looks pretty horrible if you ask me
- twerquie 13y agoIt can (and should!) be written more elegantly [5, 10, 1].sort(function(a, b) { return a - b }) Or, in ES6: [5, 10, 1].sort((a, b) => { a - b }) That's starting to look pretty nice if you ask me.
- Dirlewanger 13y agoWriting your own method to solve a problem every other language does out of the box is missing the point...
- twerquie 13y agoTrue, JS doesn't ship with a large standard library. But that has turned out to be one of its greatest strengths and a key reason for it's runaway success.
- i2 13y agoExcept it is, because your code doesn't work: > [10, 1, 5, 1, 10, 10, 1, 5, 5, 5, 10].sort(byNum) > [10, 10, 5, 1, 10, 1, 1, 5, 5, 5, 10] The right way is > function byNum(a, b) { return a - b; }
- ceautery 13y agoA bug in my code doesn't make javascript horrible, it makes me horrible for rushing to illustrate a point instead of just harrumphing internally and finishing my coffee. Good catch.
- kelseyfrancis 13y agoThe point is not that it's impossible to numerically sort an array of numbers in JavaScript; it's that calling the sort function on such an array doesn't do that. That's a surprise to most developers, I'm sure, and surprises in languages and libraries are bad.