I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.
Today I did: https://www.codewars.com/kata/help-the-bookseller
Time: 24 minutes
What I’ve learnt:
This was actually a nice challenge. Not too brain twisting, but just a nice problem to tackle.
The first thing I thought to do was to create an object with the category letters (from the second array) with reduce, and Object.assign to give me an object of letters with the value of 0.
I then did a forEach
on the through the art array (first parameter), and checked if the first letter art[0]
was a key in the object created by the reduce, then I added the price onto it. I was imagining myself in an interview, and thinking if I would go and play with regex to get the numbers out of these strings "ABART 20", "CDXEF 50", "BKWRK 25", "BTSQZ 89", "DRTYM 60"
and thought no way, I just went with `parseInt(art.split(” “)[1])` , where I split the string by the space they all had, and just grabbed the 1st index of the newly created array.
Now I have an object with the correct values, but I need to return a string like so: (A : 20) - (B : 114) - (C : 50) - (W : 0)
I used `for (category in categoryObject)` where category
gave me the key and `categoryObject[category]` the value. With interpolation I pushed this into an array outside of the for in loop, and after I returned that array with join(" - ")
.
Flying green!
What I learned from other people’s code:
Again no one liners here (except for one person, but if we copy the code to an editor with text wrap it’s on 5!).
Someone just used a forEach to add to the outer object, and therefore they did not need to worry about returning with an Object.assign. Keeping it simple! Awesome! They also chose to split the string rather than use regex.
I see I could have mapped my last array, instead of pushing it into an outer array and joining that. Duh!
Someone else used alistOfArt.reduce inside thelistOfCat.map to get the string all at once. It’s hard to know what is better to spread out, so each method is doing it’s own thing and what to combine. But great to see how it can be so compact.
Tomorrow is 30!!!! Who can believe it?!?!?!