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/change-it-up/javascript
Time: 30 minutes
What I’ve learnt: Another string manipulation here. So you can be sure I will be using charCodeAt()
though I had to keep in mind that we will need to go from z
to a
instead of continuing on with the charCode
numbers.
I used the Number.isInteger
here to check if it is a number instead of checking if it is equal to the parseInt equivalent, because I heard that can run into problems and this is the best way to check.
I used many conditionals as I worked through this, and I’m sure there is a better way if I spent more time on this. I did use the one line if statements without the brackets, I feel like they look cleaner.
Here was my solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
const vowels = ["a", "e", "i", "o", "u"] function changer(string) { changed = "" string.split("").forEach(letter => { var nextLetter = String.fromCharCode(letter.charCodeAt()+1) if (letter == "z" || letter == "Z") nextLetter = "a" if (Number.isInteger(parseInt(letter))) changed += letter else if (letter == " ") changed += " " else if (vowels.includes(nextLetter.toLowerCase())) changed += nextLetter.toUpperCase() else changed += nextLetter.toLowerCase() }) return changed } |
What I learned from other people’s code:
So again people have used regex here to seriously concise their code. I have got to start using the .replace
with regex.
I see someone using waay more conditionals than me, and with brackets aaaaannnd ;
!! Did I ever mention how ugly those unnecessary ;
are? But that’s just my opinion 😉
By the way I have figured out what ~~
does, (thanks to John!). It’s not =~~
, that was just because they were assigning it to a variable. It converts it to a number in case it was not, and then rounds it down.
Another new thing learned 🙂 Can’t wait for tomorrow!