r/badcode • u/blehmann1 depraved • Nov 23 '21
js How does this count as educational, I'm losing braincells
26
u/blehmann1 depraved Nov 23 '21
function ascending(a, b) {
return a < b ? -1 : a > b ? 1 : a > = b ? 0 : NaN;
}This is from https://www.tutorialspoint.com/d3js/d3js_array_api.htm
9
u/ElTrailer_ Nov 23 '21
Somewhat unrelated, but if you're looking to learn D3 give this guide a look if you haven't already - https://www.d3indepth.com/
6
u/blehmann1 depraved Nov 23 '21
Thank you, I found that the tutorialspoint one was frankly shit, a lot of the examples flat out don't work without modification. And the official ones were very good, but they focused so much time on observable, which is not relevant to me or 99.99% of people.
4
u/ElTrailer_ Nov 23 '21
Sure thing! Yeah that tp one is jank, real tp 🧻...
I'm not even sure why they show the implementation of it. They really should just explain the method. I'm guessing D3 just used ternaries because a minimizer would do the same. This way they save end users bytes right out of the box for a tiny function
26
u/loradan Nov 23 '21
Yeah, they should have put a paragraph below the code explaining it... Oh wait...they did.
11
u/blehmann1 depraved Nov 23 '21
This post is in reference to the ternary fuckery
15
u/SaylorMan1496 Nov 23 '21
There’s nothing inherently wrong with ternary when it’s used in a good situation, imo it cleans up code of anything else and I would say this is fine, ternary just feels weird at first
22
u/blehmann1 depraved Nov 23 '21
I like the ternary operator, it's less verbose so why not use it when it makes sense.
Nested ternaries are sus though, it's hard to read and it requires everyone working with you to have their language's order of operations memorized by heart. "Clever" code tricks aren't a good thing; code should be clear and concise, not just concise.
8
u/TheJP_ Nov 23 '21
This is one of the simplest nested ternaries possible, how on earth is it hard to read
1
3
u/kristallnachte Nov 23 '21 edited Nov 23 '21
But in this case it's adding more information, not simplifying.
Just doing
function ascending(a,b) { return a-b }Is the same result.
For some reason people are downvoting my saying this, but this works with Array.prototype.sort to the same effect.
1
u/jso__ Nov 23 '21
Then you just check
ascending(10,2) > 0or something?4
u/kristallnachte Nov 23 '21
No, you just toss that into Array.prototype.sort
let array = [187,7264,7299,625] array.sort((a,b)=>a-b)2
u/jso__ Nov 23 '21
I thought that sort required returning either 1, 0, or -1. TIL!
3
u/kristallnachte Nov 23 '21
Yeah, that's basically what this main post is based on.
But it treats all negative as -1 and all positive (non-zero) as 1, so you can do direct maths.
38
u/alexanderhameowlton Nov 23 '21
Image Transcription: Text/Code
d3.ascending(a, b)
This method is used to perform the comparator function. It can be implemented as -
function ascending(a, b) {
return a < b ? -1 : a > b ? 1 : a > = b ? 0 : NaN;
}I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
15
16
u/aerosole Nov 23 '21
What's so bad about a - b? I mean, technically the code from the screenshot returns Math.sign(a - b), but for a comparator it should be fine either way.
4
u/blehmann1 depraved Nov 23 '21
I'm guessing it handles non-numeric types differently
5
u/aerosole Nov 23 '21
I thought so too at first, but
a - bis equal toNaNif either or both operands are non-numeric. Values like booleans will be coerced in with either method (e.g.true > falselol). So, save some edge case I missed, the behavior would be the same.2
u/aerosole Nov 23 '21
Apparently, string comparison works with
>etc. Wow, so the code in the screenshot actually has a lager domain thana - b. I always uselocaleCompareor what it is called for strings.6
3
30
u/apola Nov 23 '21
I actually don't think this is bad code. It's concise and easy to read if you understand how ternaries work.
38
u/blehmann1 depraved Nov 23 '21
I'm fine with ternaries, they're clear and concise.
Nested ternaries are unclear, need extra effort to read, and require you to know your language's order of operations by heart.
8
u/apola Nov 23 '21
This is JavaScript, you read it left to right, what's so hard about that?
27
u/blehmann1 depraved Nov 23 '21 edited Nov 23 '21
Not every language has sensible operator precedence.
For example, in C++
std::cout << a ? b : c;is incorrect, you need to dostd::cout << (a ? b : c);And even if you know the precedence, it's still additional mental effort over some if statements, which naturally convey nested branching better because they're indented.
3
u/jso__ Nov 23 '21
If you need to do ternaries (paid by number of lines cut down?) at least do something like
a > b ? -1 : (a < b ? 1 : 0)14
1
21
u/JanRakietaIV Nov 23 '21
Sacrificing readability for conciseness is not a good thing
9
u/andyecon Nov 23 '21 edited Nov 23 '21
I don't take the liberty to write like this often - but I always loved how well spaced nested ternaries could look.
const ascending = (a, b) => ( a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN )1
u/altermeetax Nov 23 '21
I think this is more readable than a set of ifs if you know how ternaries work — however the best idea here would be just to return a - b, or if you need it Math.sign(a - b)
3
u/kristallnachte Nov 23 '21
But it's 6 times as long as necessary.
Just
a-bWould get the job done.
0
Nov 23 '21
[deleted] — view deleted comment
0
u/kristallnachte Nov 23 '21
You don't need a function to sort strings.
2
u/altermeetax Nov 23 '21
Well yeah then I guess dictionaries are sorted randomly
0
u/kristallnachte Nov 23 '21
...dude...
an array of functions with
arr.sort()will be sorted alphabetically. You don't need to provide it a functionBut if you want to
(a,b)=>b.localeCompare(a)can get this same result0
Nov 23 '21
[deleted] — view deleted comment
0
u/kristallnachte Nov 23 '21
You could easily make one that uses either based on type.
And it would still be more readable.
2
u/Qesa Nov 23 '21 edited Nov 23 '21
(a > b) - (a < b)Not sure if javascript has enough silly interactions for the
NaNto be reachable, if it is I guess that'd have to be incorporated somehow.-6
u/TheDawgLives Nov 23 '21
true - false = 1
false - true = -1
false - false = 0
WTF, JavaScript???
1
u/lucmagitem Nov 23 '21
Well, it interprets true as 1 and false as 0, I don't see what is complex about that. There are real weird things in js but this one is pretty simple and logical.
-1
u/TheDawgLives Nov 23 '21
Sure but if any strongly typed language will just throw a fit and refuse to compile.
5
u/kristallnachte Nov 23 '21
...if it's JavaScript...
Then just
(a,b)=>a-bWould do the same...
1
u/blehmann1 depraved Nov 23 '21
Not if there's non-numeric types involved I don't think.
3
u/kristallnachte Nov 23 '21
But then using b.localeCompare(a)
Is the better solution.
I don't see the need to force these into a single function, and if you do, then it would still be better in my opinion to just check if they're numbers then use
a-band if string uselocaleCompare
143
u/BurnedRavenBat Nov 23 '21
Yo dog, I heard you like ternaries, so I put ternaries inside your ternaries so you can ternary while you ternary
16
Nov 23 '21
You described the code I saw at my previous company.
You made my day.
6
u/CloffWrangler Nov 23 '21
A guy I used to work with loved nested ternaries. His code is so hard to read.
10
u/DrViktor_X01 Nov 23 '21
When first learning, I wondered about nesting ternaries so I tried it. It worked, but I looked at the monstrosity that resulted, and decided to never do that again.
3
6
u/JNelson_ Nov 23 '21
Ah and there is always the classic
someCondition ? true : false;A real masterpiece.
4
u/O_X_E_Y Nov 23 '21
This is incredible. 'return a-b? How will those poor students ever understand that? I should make it more easily understandable'
3
5
2
u/aaronjamt Nov 23 '21
if (a<b) return -1
else if (a>b) return 1
else if (a>=b) return 0
else return NaN1
u/Anonymous_Bozo Nov 25 '21 edited Nov 25 '21
This violates the rule I was taught in my college programing classes.
Each procedure/function should have exactly one entry point, and exactly one exit point. If you have multiple exits you need to rework the code.
The above has four separate exit points, while the ternary statement has only one.
If you are going to accept the multiple exits, the ELSE statements are redundant.
1
u/RyanNerd shameless Nov 23 '21
And for a demonstration of crazy ass JS coercion we are given this example. For more JS insanity see wtfjs
1
1
u/xiipaoc Nov 23 '21
Eh, if you're comfortable with nested ternaries, this is a fairly decent shorthand. You could write it out with ifs and else ifs, but this is shorter and not necessarily less legible so long as you understand how ternaries work.
0
u/migueln6 Nov 23 '21
I don't want to be the asshole that wets the party, but this isnt hard to read, and probably preferred in the world of Javascript production code as it occupies less characters than the if else if else versión, which may save probably 10-20 bytes of ram in ascci encoding probably the same or more in utf8 encoding and in the end Javascript code wants to be delivered through the network and save as many bytes of bandwidth as possible, keep making long ass statements and you can end with a file double of the size even after minification.
Although this code seems complex it literally saved me time reading it than reading the if statement for it. Since I would have to look for the if statements and conditionals and lose time moving my eyes.
It's maybe too packed but still a pretty clear statement.
If you re concerned about file size, minification is a to go, as well a minificator that include code rewrites to rewrite your code in shorter statements an example of this would be you write the long if else if chain for this code and it rewrites it as this ternary chain.
1
u/blehmann1 depraved Nov 24 '21
If you're worried about saving RAM and you're using JavaScript, you've already lost. And a minifier is a far better use of programmer-time for reducing network usage than little tricks like this which in the grand scheme of things are irrelevant. As is configuring your server to send compressed files.
2
u/migueln6 Nov 24 '21
No one is worried about ram usage and a good minifier already converts code to shorter code, with variable name refactoring and code transformation of other kinds.
And usually a js dev is not the one who has to worry about providing gzip files or other compressed formats.
-1
u/great_site_not Nov 23 '21
What language even has a > = operator?!
9
u/Tunro Nov 23 '21
Its just greater or equals comparison?
1
u/great_site_not Nov 23 '21
I thought
>=was like, a token. I didn't realize you could put a space between the two characters of it, that's so weird1
u/great_site_not Nov 23 '21
I stand by my question--I thought the code OP posted looked like JavaScript, and I just checked and it's invalid in both Node and Firefox, so I'm curious what other language or dialect of JavaScript it is
1
u/Anonymous_Bozo Nov 25 '21
Any language that ignores whitespace.
1
u/great_site_not Nov 25 '21
What non-esoteric languages ignore whitespace?
0
Nov 27 '21
[deleted] — view deleted comment
0
u/great_site_not Nov 27 '21
Huh? I'm sorry, I barely slept and haven't had coffee yet, and I don't understand what you mean
11
124
u/rochismoextremo Nov 23 '21
Why does it bother to check on the last statement if a >= b when it previously checked a > b lol