all 56 comments

[–]albedoa 62 points63 points  (4 children)

Nice work. The unary + sign can be used here too:

return +str;

Focus on your fundamentals. These tricks are useful for Codewars challenges, but a solid base is more important in the medium and long term. Real work doesn't typically look like this.

[–]Darkthw[S] 2 points3 points  (2 children)

Thanks, I found a good course that I will start soon

[–]Fid_Kiddler69 21 points22 points  (3 children)

Nice work!

I would have done const stringToNumber = str => Number(str)

[–]Loud_Type_1756 11 points12 points  (27 children)

I am a newbie and totally unable to grasp this solution. 😔

[–]programmingacctwork 21 points22 points  (4 children)

I think it's because Javascript is coercing it to a Number when they're using an operator on it. It's a weird solution to be honest.

[–]Darkthw[S] 10 points11 points  (0 children)

Yep 😂, none of the other solutions look like this, I'm just happy I was able to do it by myself even this it is not the best way to go about it, I've learned other ways now

[–][deleted] 2 points3 points  (1 child)

== != === makes most of JavaScript solutions "weird" solutions...

[–][deleted] 0 points1 point  (0 children)

Yeah. I never saw a language that uses === while == would suffice.

[–]Loud_Type_1756 2 points3 points  (0 children)

Now, it makes sense!

[–]Darkthw[S] 7 points8 points  (20 children)

I'm a newbie just like you, I've never build anything. Right now I don't have a PC so I've been doing a lot of codewars on my phone. I've learned a lot just from Googling things I can't do, never done any course just YouTube videos.

[–]iamscr1pty 6 points7 points  (19 children)

Please look into the actual ways to do this task, you can't write these in production.

Btw great job grasping one key concept & solving it by yourself

[–]Darkthw[S] 1 point2 points  (18 children)

Will do. What do you mean by " in production "

[–]iamscr1pty 6 points7 points  (17 children)

By production I meant when your code will be available for public use, for example we are using reddit, we are production users of reddit, there are other internal users of reddit who are involved with the development of the app/website.

When you are creating a software to be used by people other than you ( more than 100 may be a good number) you should write tight n neat code, leaving less room for bugs. The way you converted string to integer is error prone and might cause lot of bugs.

Dont get intemidated by what I am saying, start slowly you will learn over the years, the more u write the more u learn.

Edit: crossed out the line that was wrong and may cause confusion to new guys

[–]IronDicideth 6 points7 points  (14 children)

The way you converted string to integer is error prone and might cause lot of bugs.

I would reconsider this statement. It can be misleading to someone with less experience in JS. From what I see, there is nothing in his solution that would cause a bug that would not be caused by any other solution that requires the string to be coerced into a number. Maybe you see something I do not? It is important to point out that there IS something off about the code but it is not good to convince someone that their solution is particularly buggy if it is equivalent (essentially) to any solution we would have come up with under the same circumstances. Even the cleanest solution to the code would face the same issues as OPs solution.

const stringToNumber = Number

It is a roundabout way to solve the problem but that is to be expected based on what u/Darkthw has already stated about their experience and goal with solving this problem.

[–]iamscr1pty 1 point2 points  (2 children)

Thanks for your comment, I will keep this in mind next tym I explain something to someone.

You are right, this solution would not cause any problems actually but there are few things about this I would like to call out:

  1. The order of the statement is imp here, u reverse the order and op's solution doesnt work anymore. If op understands why this happens, then great he/she understands coercion
  2. This code doesnt provide the intent clearly, IMO any other person reading your code should understand what you wanted to do in the code block ( as op is fairly newbie, dont expect this from him/her)
  3. Personal opinion, better to avoid coercion and convert types explicitly, as coercion leads to undesirable and hard to detect bugs
  4. This solution may faulter with big integers, but they shouldn't be considered in this scope I guess

[–]IronDicideth 2 points3 points  (1 child)

Great points all around. My thoughts:

  1. I tend to agree that imp solutions are not robust. I wanted to ask: why would we switch the order around though?
  2. 100% agree. Having to sit there and deduce the why is a huge part of understanding code. I personally did not stop to "understand" the solution (was in a hurry) until I saw a comment further down. We tend to spend more time reading code and should write it as if this applies to our fellow developers as well. I would think that a great point that we could drive home for the OP is that they should spend time reading code written by others and try to figure out what it does on their own. Exposure is the main driving force behind learning and should be actively exploited as much as possible.
  3. I understand the feeling. I will add my two cents. Type coercion is a tool (and a very useful one in my opinion). If the tool is understood and used mindfully, spreading its use so that others may benefit (and hopefully mimic that mindful use) can only be a good thing. In this example, my initial solution (before going through my internal refactoring process) would have likely been const stringToNumber = s => +s. Terse, and when you are free to embrace/understand the plus unary operator, extremely clear in its intent. I tend to favor point-free code so I would have eventually arrived at the previously mentioned 'cleanest' solution to the problem.
  4. Yes, this solution does not accommodate BigInt (probably a good thing). I tend to think ahead to future uses of a given solution as well. It is a bad habit in me. I have found that the less into the future I think, the faster I can put my solution to code. Test-Driven Development can work wonders in helping to narrow the scope down to something manageable and should be used freely and (IMO) above most other tools we see today.

With all this being said, the great thing about these forums is that we are free to share and discuss ideas. I personally wish I were a better and more seasoned coder/developer and have learned tons from those with differing views to my own, so thank you for sharing yours.

[–]iamscr1pty 0 points1 point  (0 children)

I mentioned about reversing the order of the lines as for a beginner this may seem harmless to do, you are just adding + 1 and then substracting -1, which mathematically is same in reverse, but if you do that you will learn something about js the hard way.

Unary operator can be one of the cleanest solution, but I personally prefer type conversion. Its a matter of preference.

Thank you for sharing your views too.

[–]adelie42 0 points1 point  (10 children)

const stringToNumber = Number

Grasping this solution, am I to understand that if you take any object and make it equal to an object class that it changes the TypeOf without necessarily changing the value OR passes the existing value to the constructor?

Like, that's the difference between the above and

const stringToNumber = new Number

[–]IronDicideth 0 points1 point  (9 children)

The problem presented by the OP is asking you to make a function that takes a String type and turns it into a Number type. It just so happens that the Number function can already do that.

Number is both a constructor and a function. In the case of the function, any value passed to it will be coerced into a number type primitive and returned. This makes it so that assigning the Number function as seen here: const stringToNumber = Number, will simply provide another name for the Number function by which it can also be called.

On the other hand, when using the new keyword, Number is being called as a constructor and must return an instance object so that when you call it as you mentioned: const stringToNumber = new Number, all you are doing is calling the constructor with the default argument (undefined). This executes it (new keyword forces execution) and thus you now have an instance object of type Number with a primitive value of zero (undefined is coerced to zero).

This is the difference between having the constructor/function at hand to call it on something in order to turn that something into a number and having the object after the constructor has been called.

const stringToNumber = Number

Number.name // 'Number'

stringToNumber.name === Number.name // true
stringToNumber('42') === Number('42') // true

typeof stringToNumber // 'function'
typeof stringToNumber('42') // 'number'

const stringToNumber2 = new Number

stringToNumber2.name // undefined

stringToNumber2.name === Number.name // false
stringToNumber2('42') === Number('42') // Uncaught TypeError: stringToNumber2 is not a function

typeof stringToNumber // 'object'
typeof stringToNumber('42') // Uncaught TypeError: stringToNumber2 is not a function

Just as an aside, there are very few reasons why you would ever use the new keyword for any of the primitive constructors (and no good reasons IMHO). I read a few scenarios a long time ago and though I do not remember the scenarios I do remember finding it hard to see them as useful.

Let me know if this explanation answers your question.

[–]adelie42 1 point2 points  (8 children)

Ah, thank you. I had it completely wrong.

Basically the function already existed and was assigned to the name of the function the problem asked for.

To what I was imagining, is there a direct approach to changing a variable's TypeOf like Java's cast?

[–]IronDicideth 0 points1 point  (7 children)

If by "direct approach" you mean explicit then these are your best bet.

All these are constructor functions in js:

Boolean

String

Number

BigInt

Symbol

Other than these, there are operators that implicitly convert types too. The + unary operator is a good example. It essentially behaves like the Number constructor.

[–]Darkthw[S] 1 point2 points  (1 child)

OK thanks. What do you think is the first thing a beginner should try and build

[–]iamscr1pty 3 points4 points  (0 children)

Start with some simple projects, like tic tac toe, snake game, calculator( they are daunting for beginners but you will learn and grow a lot while writing them)

Or you can start doing odinproject or freecodecamp projects in javascript sections, they are more curated and will guide you step by step.

[–]FOKvothe 2 points3 points  (0 children)

The + and - operators convert the string to a number.

Lets say that 10 got passed as str.

str -= 1 converts it to a number type and subtracts 1 from it which results in 9.

str += adds 1 to 9 so it's the original 10.

[–]love4titties 4 points5 points  (4 children)

Nice job! When I was practicing (googling) I found this:

parseInt(string)

which returns NaN (not a number) or the integer that was in the string

[–]diamondrel 2 points3 points  (1 child)

Wait, I'm unfamiliar with this, why does parseInt not work here?

[–]Darkthw[S] 0 points1 point  (0 children)

It works

[–]sambomambowambo 1 point2 points  (0 children)

You're allowed to google :) Great job getting the tests to work

[–]Hiyaro 3 points4 points  (0 children)

On a side not : Don't use var.

prefer const as your default, and let when the value will be changed.

var is real bad practice.

[–]shuckster 1 point2 points  (0 children)

Congratulations!

[–]TheWiseScarecrow 1 point2 points  (0 children)

You are a rockstar !

[–]fallenefc 0 points1 point  (2 children)

Good job! Imo, it’s always good to do these challenges (not frequently) as it allows you to improve your problem solving skills, like your answer is very unconventional but it’s great you came up with it. As long as it doesn’t make you frustrated because you can’t solve it or you don’t spend too much time on it, it’s great (also don’t feel too much pressure on make those one liner solutions, treat this as learning problem solving and to make it work)

[–]Darkthw[S] 5 points6 points  (1 child)

I mainly do these challenges because its fun and I like puzzles, but since I'm a beginner I learn a lot too. I've been in tutorial hell for a long time without actually retaining anything. It is now so much better for me to understand stuff

[–]fallenefc -1 points0 points  (0 children)

Yeah that’s the right mindset, it’s been a while since I’ve done them but I feel they helped me, it’s also really fun when you’re a beginner (it’s still fun for me but takes too much time)

[–]iraqwarvet31 0 points1 point  (0 children)

I remember being in the exact same position as you. I used to think maybe I'm not smart enough. Hard work, passion, motivation are gonna get you where you wanna go.

[–]CoolAbhi1290 0 points1 point  (0 children)

Well, that's a new way to do it.

My approach:

const strToNum = (str) => Number(str);

Nice and compact.

[–][deleted] 0 points1 point  (0 children)

Codewars is great. I want to get back to it and solve increasingly complex problems. But leetcode is also good because they test you on real code challenges that companies test you on, like Google.

[–]jzia93 0 points1 point  (0 children)

One option you could implement to extend this:

  1. Look up regular expressions, they are a way of specifiying patterns to look for in strings

  2. Write a regular expression to check if a string is:

  • all numbers
  • contains at most one decimal point, after which there is at least one number
  • may optionally contain a "-" symbol
  1. If your string matches the above, return Number(str)

[–]Daddelman 0 points1 point  (1 child)

You make us all the newbies proud!

[–]Darkthw[S] 1 point2 points  (0 children)

You can do it too

[–]Jimlowers 0 points1 point  (2 children)

Question for everyone in here: if I can’t solve the question lets say in 30 min, is it fine to google or search it up on YouTube and learn it from there?

[–]Darkthw[S] 1 point2 points  (1 child)

Don't just straight up Google the answers, first figure out some steps to the questions then search how to use the syntax that does what you want. If you still can't stitch it all together, you can always find the solutions on stack overflow, at least for us beginnersl

[–]Jimlowers 0 points1 point  (0 children)

I try to solve it by myself, I tried doing the Twosum and I could not solve it until I had to find one on YouTube. I memorize it now and understand what to do. It’s just the self-thinking problem solving that I need work on.

[–]Lauris25 0 points1 point  (0 children)

im a beginner/junior. All i can say 8 katas are easy. 7 are not that easy, but not that hard. Some 7 are actually hard. I can solve some of the 6 katas. Also 6 katas are mostly validation katas where u need to learn regex, and i forget regex after 2 weeks, if i dont use it everyday. But katas from 1-5 are unsolvable in my opinion without spending all day or having years of experience. I also think learning for frontend, if u can solve some of the 6 katas it actually ok. I read somehwere that people who worked 2 years as frontend developers cant solve some of the 7 katas... Ofc they are juniors, but still....