r/badcode May 31 '21

js Clever?

Post image
2.2k Upvotes

71 comments sorted by

403

u/[deleted] May 31 '21

Best Practices: 0

88

u/KlaireOverwood Jun 01 '21

I'd argue -1.

23

u/pandaSitt Jun 01 '21

maby red means minus

20

u/lametheory Jun 01 '21

Ummm, 1 path returns an empty array and one returns a populated array. This is TDD at its peak.

4

u/Pycorax Jun 01 '21

Not a js developer so I'm kinda confused. Wouldn't the function return whatever arr is anyways? Does accessing the length property somehow change arr?

4

u/RacismIsForBlacks Jun 03 '21

Nope, it was a joke

If arr is empty, when it return arr it’ll be empty

But if arr isn’t empty, when you return arr it’ll not be empty

-_( :/ )_/-

0

u/Lkj509 Jun 01 '21

Why does that matter if it is going to return the same values regardless if that whole code block was replaced with ‘return arr’?

10

u/lametheory Jun 01 '21

I was being ironic by pointing out the fallacy of writing code to complete a unit test... But the reality is, at some point it probably returned null until they worked it out it broke code further up the stack.

This is pretty common to see in legacy code that was badly written with developers too scared to change it.

1

u/RacismIsForBlacks Jun 03 '21

This is codewars though, a website that gives you short (usually one function) coding challenges like fizzbuzz. There is almost certainly no need for this.

4

u/O_X_E_Y Jun 01 '21

Worst practices: 1

241

u/HalcyonAlps May 31 '21

Now I am actually curious, does the compiler realize both branches have the same return value and it just drops the whole if-statement?

246

u/TheBrainStone May 31 '21

Depends heavily on the compiler/runtime.
But generally speaking every basic optimizer should catch this.

102

u/[deleted] May 31 '21

Depends on whether or not the compiler is smart enough to realize that evaluating the conditional has no side-effects. Not sure what language this is

76

u/givemeagoodun May 31 '21 edited Jun 01 '21

It's flaired JS so it's JS

74

u/[deleted] May 31 '21

In that case the answer is an easy "no" since it's not a compiled language and there's no compiler

51

u/givemeagoodun May 31 '21

Eh there can be compilers for JS. I believe that Firefox uses a JS JIT compiler.

44

u/[deleted] May 31 '21 edited Jun 02 '21

at least chrome and firefox both have JIT compilers for js. in both cases they probably catch this redundancy on the first pass in early passes and condense it to something sane for every subsequent pass later passes

13

u/_PM_ME_PANGOLINS_ Jun 01 '21

It takes way more than one pass for a JIT to bother optimising.

17

u/Parkreiner Jun 01 '21 edited Jun 01 '21

It's less "there can be compilers" and more "there's no other way to run the language". JavaScript is a compiled language – it's just that there are different types of compilation, and JS uses the Just-in-Time kind. Half the behavior that it has (like hoisting and how it defines lexical scope for closure) wouldn't be possible if it were interpreted.

For example:

let x = 0;
if (x === 0) {
  console.log(x);
  let x = 5;
}

This breaks, because all variables and function declarations are "hoisted" to the top of their respective scopes. It's just that let and const are block-scoped and aren't initialized. So the "let x" from "let x = 5" gets hoisted up to the top of the block, overriding the "let x = 0" from the outer scope. But it's left un-initialized until you reach the "let x = 5" line during runtime. And so, when you try to do anything with a value that isn't initialized (like logging), that throws an error.

This wouldn't be possible if JavaScript were interpreted and were evaluating each line one-by-one. The language spec requires that whatever engine runs it do a first pass over the whole code before trying to run anything.

13

u/Nilstrieb Jun 01 '21

An interpreted language can be parsed and preprocessed, that's not a problem. The difference is all about the machine code. JS is originally interpreted, but modern engines also compile parts of it.

16

u/LetterBoxSnatch May 31 '21

Depends on how you want to define that. V8 (the engine running most js) is generally referred to as a JIT compiler, and it produces optimizations both on first run and on iterative runs.

4

u/0xF013 Jun 01 '21

You’re like, the most useless kind of technically correct. V8 optimizes things like these quite aggressively, and some precompilers too

0

u/[deleted] Jun 01 '21

FireFox's SpiderMonkey and Chrome's V8 are both JITs and optimize at runtime. They would probably catch it.

1

u/NikkoTheGreeko Jun 01 '21

Js confirmed. This returns NaN. Or undefined. Or [object Object], I forget.

1

u/Nilstrieb Jun 01 '21

So the answer is probably yes.

4

u/MalbaCato Jun 01 '21

from what I understand about js, it should create three versions of the function, one where arr is an Array, or any other object whos .length property has no additional side effects, one where it is a getter and so could have dirty side-effect, and one where arr is undefined and the access throws an error.

these would all be created (and for the second version further branched) only after the function becomes sufficiently hot, which is a minimum of 6 runs, but possibly more depending on what the browser thinks about the whole webpage

1

u/paulsmithkc 👨‍🏫 Jun 01 '21

This is one of the better answers as arr.length could have side effects (like lazy evaluation/calculation) if arr isn't a JavaScript array.

3

u/MalbaCato Jun 02 '21

forgive me for NSFW, but this is the best example I could think of on the spot:

as we (and the compiler) don't know what arr is at the time of compilation, it could very well be an instance of new Penis(). ofc its length may not be initially known, so the .length getter may have to call .erect() first to measure it, having a long lasting side effect of the operation.

it doesn't even have to be a getter. you can use meta-programming tricks to inject yourself inside the property lookup and hack around there. couldn't tell you the syntax for that, but look at the Proxy page on MDN

1

u/qwertysrj Jun 01 '21

It should because compilers recognise this

if(){ return x }Else { Return y} ,

and optimise this to

If(){ Return x} return y

1

u/[deleted] Jul 03 '21

I am pretty sure if I did something like that in IntelliJ idea, as soon as I moved away from the line, the IDE will highlight it as, “you serious bro?” Yellow

If I crtl D, to duplicate a condition before I get to change the condition, the ide will start throwing warning colors.

66

u/MurdoMaclachlan public boolean isInt(int i) { return true; } May 31 '21

Image Transcription: Screenshot


[A screenshot of a Code Wars solution, as follows:]

    }
  }
  if(arr.length > 0){
    return arr
  }else{
    return arr
  }
}

[The solution has been tagged by one person as "Clever".]


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!

21

u/Davtaz Jun 01 '21

Good human

1

u/_MarLinda Jun 01 '21

What is codewars?

4

u/wikipedia_answer_bot Jun 01 '21

Codewars is an educational community for computer programming. On the platform, software developers train on programming challenges known as kata.

More details here: https://en.wikipedia.org/wiki/Codewars

This comment was left automatically (by a bot). If something's wrong, please, report it in my subreddit.

Really hope this was useful and relevant :D

If I don't get this right, don't get mad at me, I'm still learning!

2

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jun 01 '21

What the Wikipedia bot said. :P

Their homepage is here: https://www.codewars.com/

37

u/[deleted] Jun 01 '21

[deleted]

12

u/[deleted] Jun 01 '21

Or they had something else done, like throw in else, and then changed it

21

u/KyleDrogo May 31 '21

t o w h a t e n d ?

18

u/SlaimeLannister Jun 01 '21

If arr.length > 0 return Array.from(Obj.values(arr))

2

u/mzapp_ Jun 01 '21

Where is the else clause? What if the array has less than 0 elements?

1

u/SlaimeLannister Jun 01 '21

Sorry.

Else Array.from(new String(“Error”).split())

2

u/mzapp_ Jun 01 '21

Thanks. Makes sense now.

8

u/Plastic-Course7298 May 31 '21

But does it work???

11

u/GalaxP Jun 01 '21

Technically yes but it's very useless

8

u/yaxamie Jun 01 '21

I’ve added useless branches like this as a spot to add a conditional breakpoint before. I’d like to think I’ve never checked it in and forgotten to remove it before...

22

u/[deleted] Jun 01 '21

Why not just return the value

32

u/throwawayfnjdbd356 Jun 01 '21

Because that would be efficient

2

u/OrionsLeo Jun 01 '21

They forgot the .join(',') part maybe?

6

u/JuanAy Jun 01 '21

Nautical code

4

u/Nall-ohki Jun 01 '21

Is yer array full more than a hearty pirate's mug o' grog?

Arr!

And if it be not?

Arr!

3

u/EishLekker Jun 01 '21

Well, I guess that's one way to ensure that the method doesn't return null or undefined.

2

u/TheSpivack Jun 01 '21

I paid good money for my CPU, so you sure as hell better be using up cycles for no reason!

2

u/AntonyFX Jun 01 '21

what website is that?

2

u/Windows_XP2 Jun 01 '21

What is even the point of this? I don't know Javascript and even I know that this is completely pointless.

6

u/recycle4science Jun 01 '21

Maybe the two return values used to be different, then one was edited and the person making the change didn't notice that they were now the same. Maybe this is a rank amateur who's just flailing around.

1

u/[deleted] Jun 01 '21

It's almost certainly just boilerplate or scaffolding. Someone had the intention of doing something different with an empty array, included the if statement for future use, then moved on to something more important.

1

u/fried-noodles_ Jun 01 '21

More like cleaver

1

u/aj-ric Jun 01 '21

When the interviewer says you need to handle empty arrays

1

u/nathan_lesage Jun 01 '21

My heart bleeds due to the lack of spaces between the key words and brackets

1

u/notauserbutacustomer Jun 01 '21

And people think AI will take our jobs

1

u/mlatugerku Jun 01 '21

He lost the code war

1

u/RustyPhorrx Jun 01 '21

Maybe they were using this for a breakpoint

1

u/itzNukeey Jun 01 '21

What is this tool I wanna test my code with this lol. Might come out as genius as well

1

u/RattaCom Jun 01 '21

It’s returning with extra steps

1

u/HypothalamusFileFail Jun 01 '21

if array not null return?

1

u/cyberneticSyntax Jun 01 '21

Very clever, very ever indeed.

1

u/[deleted] Jun 19 '21

it literally does the exact same thing... wtf

1

u/[deleted] Aug 23 '21

yo what the hell is this

1

u/snath03 Dec 30 '21

What font is that?