this post was submitted on 05 Sep 2023
913 points (98.7% liked)

Programmer Humor

19589 readers
589 users here now

Welcome to Programmer Humor!

This is a place where you can post jokes, memes, humor, etc. related to programming!

For sharing awful code theres also Programming Horror.

Rules

founded 1 year ago
MODERATORS
 
top 50 comments
sorted by: hot top controversial new old
[–] aksdb@feddit.de 133 points 1 year ago

Looks like they should have called that function sortOf()

[–] Konlanx@feddit.de 56 points 1 year ago (3 children)

This is due to the default sorter in JavaScript sorting by the string value. The reason for that is that this won't create errors at runtime. Since JavaScript does not have types, this is the safest way of sorting.

This works:

const unsorted = [1, 100000, 21, 30, 4]
const sorted = unsorted.sort((a, b) => a - b) 
[–] jmcs@discuss.tchncs.de 66 points 1 year ago (1 children)

Which is a fine decision if you have a programming language to do silly stuff on a personal geocities page, but a horrible one when you start using that language to handle serious data. Silently ignoring what's probably a bug is dangerous.

[–] seitanic@lemmy.sdf.org 25 points 1 year ago (1 children)

Which is a fine decision if you have a programming language to do silly stuff on a personal geocities page

And that is, of course, what it was designed for.

JS is brilliant considering that it was created by one dude in 10 days. Nobody thought it would become nearly as important as it has become.

[–] luciferofastora 1 points 1 year ago

Nobody thought it would become nearly as important as it has become.

This is why I'm wary about all the quick and easy "temporary" solutions I'm building because I don't have the time to do it properly, and pushing hard to replace them with a more solid permanent one at any chance. I'm already mortified at the idea of someone proficient ever looking at any of it in the inevitable event of it becoming a long-term fixture.

[–] UndefinedIsNotAFunction@programming.dev 11 points 1 year ago* (last edited 1 year ago)

Get out of here with your sensibility!

^kidding, ^js ^via ^ts ^is ^my ^life.

[–] AVincentInSpace@pawb.social 1 points 11 months ago* (last edited 11 months ago)

ah yes, a reasonable solution to that problem that any human would think of

ah yes, a reasonable problem that any human would think of -- "what if someone tries to sort a list containing some integers and some arrays, and our interpreter needs to keep chugging instead of telling the programmer they fucked up?"

[–] seitanic@lemmy.sdf.org 37 points 1 year ago (3 children)
[–] zqwzzle@lemmy.ca 19 points 1 year ago (1 children)
[–] luciferofastora 1 points 1 year ago

For those unfamiliar with the magic behind this, the rough outline goes like this:

++ is an operator to increment a number.
The string 'a' can't be incremented, because it's not a number.
++'a' thus evaluates to NaN (Not a Number), which in turn is converted to the string 'NaN'.

The string concatenation expression is thus equivalent to 'b' + 'a' + 'NaN' + 'a' which evaluates to 'baNaNa' and is then lowercased to 'banana'.

(You could get more pedantic about the exact evaluation mechanisms and order, but if you're proficient enough to make sense of that, you probably didn't need the explanation in the first place)

[–] fraction@feddit.de 9 points 1 year ago

Based on this you can Take Shit even further with jsfuck

[–] StarkillerX42@lemmy.ml 3 points 1 year ago* (last edited 1 year ago) (1 children)

"Actually, this one isn't 'Wat', it's part of what makes Ruby awesome and powerful, unless of course you actually do this, at which point it's 'Wat'"

[–] Zeragamba@lemmy.ca 3 points 1 year ago* (last edited 1 year ago)

let's talk about Ruby

Ruby like most programming languages doesn't support bare words, [undefined variable exception]

but if you define a particular method_missing, suddenly Ruby supports bare words. [ruby repeating what was typed]

Now this isn't deserving of wat. this actually shows just how awesome Ruby is. [Drummer_t-rex.jpg]

But if you actually do this then....

Wat

[–] LanternEverywhere@kbin.social 36 points 1 year ago (9 children)

As a non-programmer, why does it do this? Sorting by leftmost digit seems super dumb.

[–] fidodo@lemm.ee 18 points 1 year ago

You can put any type of value in an array in JavaScript. You can have numbers, strings, booleans, arrays, and objects. So what should the default sort function sort by? Sorting by numbers makes sense, but what if it wanted to sort strings instead?

When you don't know what value is in an array ahead of time you can't assume how to sort it. When you're controlling the program you can provide a sort function for the type of values you know will be in it, but when you're writing the standard default sort function, there's only one type that you can convert all the other types to safely and simply in the most predictable way, which is strings.

[–] KiofKi@feddit.de 15 points 1 year ago (1 children)

"By default, the sort() function sorts values as strings.

This works well for strings ("Apple" comes before "Banana").

However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

Because of this, the sort() method will produce incorrect result when sorting numbers."

https://www.w3schools.com/js/js_array_sort.asp

[–] floofloof@lemmy.ca 8 points 1 year ago

It also produces incorrect results in many languages other than English. You can pass it a compare function that uses localeCompare or Intl.Collator to get a correct alphabetical sort.

[–] Blackmist@feddit.uk 14 points 1 year ago

Because it turns everything into text first. Just in case you try to sort [1,"apple",45.99,false,[true,3]] rather than an array of similar things like a normal person.

[–] jormaig@programming.dev 9 points 1 year ago (1 children)

Because when it's sorting some of them as ints and some of them as strings. JavaScript has implicit conversion to string.

[–] kevincox@lemmy.ml 5 points 1 year ago (1 children)

Wrong. JavaScript sort's default comparison function always converts to strings.

[–] jormaig@programming.dev 3 points 1 year ago (1 children)

Only if one of them is a string right? If you have only numbers then it works fine right? Right? (Please say that I'm right 😭)

[–] kevincox@lemmy.ml 5 points 1 year ago* (last edited 1 year ago)

No. It always compares by converting to string. I actually think this is more consistent then having different behaviour if you have a string somewhere in your list.

Basically the default comparator is a.sort((a, b) => `${a}` < `${b}` ? -1 : 1).

[–] reverendsteveii@lemm.ee 9 points 1 year ago (1 children)

Think of digits like you would letters. You're essentially sorting numbers alphabetically. It's not the right way to do it, of course, but it's the natural way to do it using a system like computers use that doesn't necessarily differentiate between digits and letters unless you tell it to specifically.

[–] CheezyWeezle@lemm.ee 3 points 1 year ago (1 children)

I think the main shortcoming here is that there isnt a way to specify the type to sort as, instead you have to write the function to compare them as numbers yourself. If it's such a simple implementation, why isn't it officially implemented? Why isn't there a sortAs() that takes two args, the input list, and a Type value? Check every element matches the type and then sort, otherwise return a Type Error.

[–] reverendsteveii@lemm.ee 1 points 1 year ago* (last edited 1 year ago) (1 children)

I mean, there's a sort() method that takes a comparator(a,b) such that if a comes first it returns 1, if b comes first it returns -1 and if they're equivalent wrt sortinf it returns 0. If you absolutely need type safe number sorting you can use that to get it.

[–] CheezyWeezle@lemm.ee 2 points 1 year ago (1 children)

Right, but you have to make that comparator yourself, it's not a built-in part of the language. The only built-in comparator converts values to strings and compares them in code units orders.

Also, that technically isnt type-safe, is it? If you threw a string or a NaN at that it would fail. As far as I knew, type safe means that a function can handle type errors itself, rather than throwing an exception. So in this case the function would automatically convert types if it was type-safe to prevent an unhandled exception.

[–] reverendsteveii@lemm.ee 2 points 1 year ago (1 children)

Not every use case can be the built-in default. I wouldn't have made JS weakly typed if I were designing it, but once the decision was made to use weak typing it made sense to either have no default sort method or to have a default sort method that assumes a type.

What I've outlined for you is the interface for a comparator, not the implementation. You can type check and convert and do anything else you want under the hood of the comparator you write.

[–] CheezyWeezle@lemm.ee 2 points 1 year ago (1 children)

It doesn't have to be the default to be built in, tho. It could be an overloaded function, having the "default" be the typical convert-to-string sorting, and an overloaded function that allows to specify a type.

It's just such a common thing, wanting to sort a list by different types, that I'm surprised there hasn't been an official implementation added like this. I get that it a simple "fix" to make, but I just think that if it's that simple yet kind of obscure (enough that people are still constantly asking about it) there should be an official implementation, rather than something you have build yourself.

[–] reverendsteveii@lemm.ee 2 points 1 year ago (1 children)

Thats just JS for you. If you're being generous, it's a "quirky" language. If you're being ungenerous, it's a steaming pile of arbitrary decisions, gotchas, unexpected behaviors and problems that no one bothered to solve because there's a workaround.

[–] CheezyWeezle@lemm.ee 1 points 1 year ago

Yeah, JS always seemed like the red-headed stepchild of modern languages. I'd be curious to know if other ECMAScript languages like JScript are as, eh, "quirky", suggesting that the ECMA spec is the source of the quirkiness, or if JavaScript itself is the one making silly decisions. Technically, I mostly work with Google's AppScript when I use ECMAScript stuff, but I'm fairly certain AppsScript is based off of JavaScript instead of directly based on the ECMA spec, so I don't think it's separate enough for me to draw a conclusion there.

[–] nero@lemmy.world 1 points 1 year ago

It sorts them based on their unicode character, not the actual numbers. 1 is U+0031, 2 is U+0032, etc.

[–] jdeath@lemm.ee 1 points 1 year ago

it's lexicographic order

load more comments (1 replies)
[–] Squirrel@thelemmy.club 26 points 1 year ago

Because everyone means "alphabetize" when sorting numbers.

[–] Rozauhtuno@lemmy.blahaj.zone 20 points 1 year ago (1 children)

JavaScript was made in 2 days through a drunken stupor, and it shows.

It's sad to have the rushed ramblings of a bigot become the fundamental block of the modern world wide web. Why couldn't it be at least made by a more competent bigot like Carmack?

[–] nintendiator@feddit.cl 5 points 1 year ago

Honestly this being javascript I expected the answer to be

[4, 1, 100000, 30, 21]

(sorted alphabetically by name)

[–] Armand1@lemmy.world 3 points 1 year ago (2 children)

As annoying as this is, you are meant to use a comparer.

mapped.sort((a, b) => {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  return 0;
});
[–] minikieff@lemmy.world 37 points 1 year ago (1 children)
arr.sort((a, b) => a - b);
[–] SpyingEnvy@lemm.ee 2 points 1 year ago

One hundred percent how I do it everytime.

[–] smik@discuss.tchncs.de 5 points 1 year ago

Stuff like that exists to remind us of the Java in JavaScript

[–] nao@sh.itjust.works 1 points 1 year ago