If I had to guess this was an assignment and the writer misunderstood what it means to "reverse" an int and the assignment specified that you may/should use string conversion.
Wow Tim is a real beast. O(heat death of the universe) is in constant time which makes it O(1). Thats very efficent if i want to compute it for numbers > heat death of the universe. Give him a raise!
function reverseNum(number) {
const j = Math.abs(number);
let result = number;
for (let i = 0; i < j; i++) {
result -= 2;
}
if (number + result == 0) return result;
for (let i = 0; i < j; i++) {
result += 4;
}
return result;
}
It was an attempt at humor (which apparently crashed and burned as much as that code), implying that that code is offensive (tbh, it does hurt my eyes).
Though that's in no way meant to de-value your effort in writing it out.
JS number parsing goes from left to right until it encounters a symbol that doesn't fit. Integers do not have a decimal point, so in your example it'll just stop after 6 and ignore the rest. If the first symbol isn't valid it'll just stop and return NaN.
If you want something unicode-aware you'll probably have the best results with Julia. It's tuned for maths, so it supports things like Px as variable name and doesn't have an issue with 2x instead of 2*x.
It's not what I want or expect. I was mostly just trying to point out, that expecting a standard library integer parser to support unicode expressions is probably expecting too much, because really, where would it end?
Even in Julia, I'd expect this case to be more a matter of some eval() function than of a number parser.
Also, the original intent was just a joke about what might be even worse in the OP.
Campbell's 4th law: "Any code snippet in a forum that allows comments will be followed by comments showing how it could be done with less code, and often further followed by satirical examples of even worse ways to do it. Usually in Java."
It depends on the level of enterpriseyness you want to go with.
I mean if you want to create a factory that produces a FalseReturner class that has one function (guess which one), you can knock yourself out being all smart in the big enterprise. I'm not saying your coworkers will like you for it, but it has certainly happened.
To be fair, when working with any network-transmitted data, it's runtime type checks or prayers that are the only real answer, and that's not JS specific.
Depending on how you use it. For return statements like in the post I would disagree. For assignment I would most definitely agree because it's just much more readable
Reversing a string is a common question for interviews. Wouldn't surprise me if this came from one. It's an airball on multiple levels, but I've seen worse.
Pretty new to coding here, but from what I understand this code is basically trying to switch the sign of a number from either negative to positive or positive to negative, but in a regally dumb way by nonsensically converting int to string? Is parseInt supposed to coerce the result back to an int?
I think this is an inexperienced dev that pictured the numbers in his head, went "I just need to remove add the (-) sign in front of it" then figured he could use the string representation to manipulate this character as he envisioned it.
Or it's a troll meant to look bad.
But to be honest I have seen too many instances of people following the first approach: Almost no reflexion is made on "is this really a sane way to do things?" They just don't take any step back and stop at the "it works"...
if the string representation of a number (say "-34") contains the '-' char, then return the integer representation of the string without the '-'. If the string doesn't have a '-', add one and return the integer representation of that.
aka make negative positive, and positive negative.
edit:
This should really say that we're looking for a '-' char in the passed and returning everything after the first one found, attempting to turn that into an int. given a hyphenated name, this blows up. Given a telephone number with '-' as a delimiter, this blows up, etc. Additionally, if no hyphen is found we add one to the front, and try to turn it into an int. there is no actual check that numeric values are being passed, that they aren't decimals, etc. Hopefully this is done in the code before the value is passed. . .
+ operator on strings is concatenation in JS thus in:
var num = 34;
var stringNum = num.toString();
var result = "-" + stringNum;
result will have the value of "-34", as a string. The pass to parseInt in turn swaps the datatype to int (well it attempts to return an integer with the value of the string, and is easy to break).
As a lot of you i read the function name and was thinking ohh that makes sense to have a function changing 123 to 321 would be more understandable to be a function. But this is a total disaster
I'm surprised no one's mentioned the num.toString() function, which will make autoboxing kick in. The value of num gets converted into an object so that it becomes something with access to the toString method, and then the method gets called, basically throwing the object away.
Nobody should fault you for not understanding this snippet. It's nonsense. It takes a simple solution and creates a mountain of problems.
Edit: Most devs approach things like this as if the writer knew what he was doing. Certain assumptions go into reading a thing that should be universal. That's not the case here. As long as you can break it out into the simplest parts and understand those parts one at a time, you're going to be fine. Practice makes it faster.
I've been in the industry for 10 years and have a title that currently includes both "Senior" and "Architect" and to this day, I have to google things all the time. Also it took me like 40 seconds to understand what this code was doing.
Programming is a high barrier to entry and you're doing fine. Keep it up, it's worth it!
That's the main difference between good and bad code. You should be able to read out loud the code and it should make sense and it should be easy to follow even by non-programmers. Otherwise you generally have to refactor it.
Of course there are some exceptions. If (and only if) the code is identified as being slow, then it can be optimised, which will make it less readable in most cases.
Of course I'm talking about high level languages. With low level languages the code is generally less readable, but the dev should still try to make it as readable and self describing as possible.
This code is bad because it's hard to understand quickly, it's a needlessly complicated way to accomplish something. If code on this subreddit takes you longer than normal to understand, don't let that make you feel self conscious. A lot of the code here is bad because it's hard to follow what it's doing.
It takes more than the usual time to understand for everyone, although perhaps for different reasons. That's what makes it belong in this sub.
I understood what all the parts do individually, but still got hung up on how they were combined. First of all, the function name doesn't match what it does. Especially converting to the string in the first line reinforced in my brain that it was supposed to reverse the digits. That's where experience maybe even hurt me, because I have seen many reverse functions start out that way. I'm guessing they may have even copied this first line from an online source.
The next thing that slowed me down was them using stringNum.includes instead of startsWith. That got me thinking about cases where a - was in the middle of the number. Maybe this was some sort of uuid instead of an integer? That would make the toString at the start a bit odd, but this is/r/badcode after all.
The next line had quite a bit of nesting, and again was more complex than necessary because the - is always going to be at the beginning, but it was written as if one could appear anywhere in the middle. There was no handling for multiple minus signs, so at this point, I was still thinking about a string like 123-456.
Then I read the last line that just prepended a - and it all came together.
That really feels like overanalyzing when I read it back, but in general, it's safest to assume that code was written in an unusual way for a reason, because there is some boundary case I haven't considered. My brain wants to find that reason, but sometimes the reason is the author was very confused.
This is one of the rare examples where I don't have to read it out loud multiple times to actually understand what's it supposed to do and what's the issue with that, and I'm a senior. Like the other guy said, part of the reason it's bad code is because it's not even clear what the target is supposed to be.
Don't get discouraged, continue to grow and listen to your peers when it comes to practice and you'll do fine.
You are a junior dev and that's why it is not immediately apparent what the point of this is. It takes years of experience seeing countless lines of shitty code to quickly guess what the person is trying to accomplish.
Do NOT sweat this stuff, for sure. Even if this were the best way to do this, reading code takes time and practice. "Everything is hard to read until you learn to read it." -- Rich Hickey
3
u/campbellm Aug 31 '21
"Do I need to be good at math to be a programmer?"
Send them this.
515
u/XKlXlXKXlXKlKXlXKlXK Aug 31 '21
First two lines made me think the function will make 321 out of 123. But no. Oh no.
96
u/[deleted] Aug 31 '21
Image Transcription: Code
[Dark Theme.]
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!
67
u/[deleted] Aug 31 '21
or just... return -num??????
153
u/R3D3-1 Aug 31 '21
Bonus points if it turns out that it isn't a hyphen but a Unicode minus sign.
21
u/propostor Aug 31 '21
I like how people in the comments are suggesting how this function should really be written.
When really function doesn't need to even exist.
36
u/[deleted] Aug 31 '21
return num *= -1;
Would that work? I don't JS
25
u/[deleted] Aug 31 '21
x * -1
math class was useful for once
13
u/Detfinato Aug 31 '21
Reversing a string is a common question for interviews. Wouldn't surprise me if this came from one. It's an airball on multiple levels, but I've seen worse.
5
u/paraiahpapaya Aug 31 '21
Pretty new to coding here, but from what I understand this code is basically trying to switch the sign of a number from either negative to positive or positive to negative, but in a regally dumb way by nonsensically converting int to string? Is parseInt supposed to coerce the result back to an int?
2
u/amalgamatecs Aug 31 '21
This is a leetcode question.
3
u/Impossible_Average_1 Aug 31 '21
This is how
actually works internally.
2
u/oNamelessWonder Aug 31 '21
I don't wanna be cocky but, is this what happens when you learn programming from youtube while having absolute zero knowledge of simple math?
1
u/ososalsosal Aug 31 '21
Well that's one way to do it
1
u/PeterPook Aug 31 '21
Its almost as if the abs() function doesn't exist...
1
u/SoLongAndThanks_ Aug 31 '21
N I C E
1
u/Squabbler Aug 31 '21
What colorway is this?
1
u/stahkh Aug 31 '21
When you are not allowed to use multiplication.
1
u/StarkOdinson216 Aug 31 '21
Oh my god what the fuck does this even do
1
u/il-est-la Aug 31 '21
Technically the truth
1
u/AvakumaMorgoth Aug 31 '21
1
u/Minteck Aug 31 '21
I wonder what the
parseIntfunction actually does.1
u/c4p5L0ck Aug 31 '21
Incase it's a phone number of course. Duh
1
u/hob814 Aug 31 '21
As a lot of you i read the function name and was thinking ohh that makes sense to have a function changing 123 to 321 would be more understandable to be a function. But this is a total disaster
1
u/planktonfun Aug 31 '21
here you go:
"hello world".split('').reverse().join('')
1
u/kreetikal Aug 31 '21
I remember doing something like this a long time ago...
1
u/h7x4 Aug 31 '21
Smells like someone has been coding past 4AM
1
u/Voxelgon_Gigabyte Sep 01 '21
the intern contributing to the codebase
1
u/Parkreiner Sep 01 '21
I'm surprised no one's mentioned the num.toString() function, which will make autoboxing kick in. The value of num gets converted into an object so that it becomes something with access to the toString method, and then the method gets called, basically throwing the object away.
It'd be better to just use the String function.
0
u/[deleted] Aug 31 '21
[deleted] — view deleted comment
0
u/[deleted] Aug 31 '21
[deleted] — view deleted comment
0
u/[deleted] Aug 31 '21
[deleted] — view deleted comment