Day 16 of 30 of Codewars – Javascript

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/prize-draw/

Time: 60 minutes

What I’ve learnt: So I was super surprised that this one took me an hour (with some breaks in between doing other stuff)!  But I was really thinking of a way to store the winner, before I full read the kata I thought I was just storing one winner so I wanted to create an array of the winner, so as I iterated I could store the highest scoring winner along with their name, so I tried

array[0], array[1] = <name>, <score>

and sadly that did not work (it works in ruby!). So then I changed it to `array = [<name>, <score>]`, and that worked, but then I realized I need all the names in order so I could choose the n number of them and return that one.

Sooooo, I decided an array of objects is my best bet, and tried this array.push({name: score}), only to realize that I can’t use a variable name as a key in the object like that. So again learning new things. (And this sounded like an easy kata lol). So the way to do that was to put a bracket around name: {[name]: score}, but by then I had already changed my mind and thought it would look cleaner (and easier to sort!) if I named it like this: `array.push({name: <name>, score: <score>})`.

So now after a for loop, split(""), reduce, with charCodeAt -96 (all the letters were converted `toLowerCase()`, and then * by the `weight[i]` I had my `score` (and name was from the array.split("")[i]) to push in the winners array.

Now I created a variable and did `winners.sort(a, b =>  a.score > b.score)`, and it was interesting to see that sort mutated the winners array, so got rid of the variable and continued using the mutated array. So I first sorted by name, and then by score, and all was good in the world until I got to the final tests, and the random tests were failing. And for some reason, my arrays were not all being sorted :(.

[ { name: ‘Olivia’, score: 444 },
{ name: ‘Elizabeth’, score: 485 },
{ name: ‘Matthew’, score: 485 },
{ name: ‘Lagon’, score: 162 },
{ name: ‘Addison’, score: 365 },
{ name: ‘Robert’, score: 420 },
{ name: ‘Olivai’, score: 444 },
{ name: ‘Lily’, score: 372 },
{ name: ‘Lyli’, score: 310 },
{ name: ‘William’, score: 344 },
{ name: ‘Willaim’, score: 344 },
{ name: ‘Noah’, score: 84 },
{ name: ‘Grace’, score: 156 },
{ name: ‘Abigail’, score: 288 },
{ name: ‘Sofia’, score: 165 },
{ name: ‘Madison’, score: 328 },
{ name: ‘Sophia’, score: 148 },
{ name: ‘Liam’, score: 117 },
{ name: ‘Ava’, score: 108 },
{ name: ‘Avery’, score: 76 },
{ name: ‘James’, score: 53 },
{ name: ‘Daniel’, score: 51 },
{ name: ‘Aiden’, score: 38 } ]

So I had to get a better sort going, though I am not really sure why this didn’t work on the random tests, but the initial tests it was fine on. So I literally returned where each position should go based on if statements:

1
2
3
4
5
6
  winners.sort((a,b) => {
    if (a.score == b.score) return a.name.toLowerCase() > b.name.toLowerCase()
    if (a.score < b.score) return 1
    if (a.score > b.score) return -1;
    return 0;
  })

 

And then returned the winners[n-1].name and we were flying green!!!

So I think I’ve learned about objects, and sort in this lab. Though I will need to follow up why the built in did not work for me.

What I learned from other people’s code:

So I did see that people did have to hack into their sort method. I’ve gotta say I’m pretty happy with my solution overall, and see I did not overcomplicate things. It’s interesting to note how in some people’s sort() they use a.score – b.score. This will return either a positive or negative number so that will tell it where to place it. Very nice! (Here’s a nice link on sorts – http://www.javascriptkit.com/javatutors/arraysort.shtml)

Happy learning until tomorrow!

 

 

Day 15 of 30 of Codewars – Javascript

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/the-maximum-sum-value-of-ranges-simple-version

Time: 10 minutes

What I’ve learnt: This kata I started with a for loop on the ranges. I then created a new array based on the start and end range (range[0], range[1]) with slice as not to manipulate the old array (because we will use it on each range!). Then I reduced this new array to get the total. (Hurray for using reduce!). I then created a variable outside the loop called maxSum, and set it equal to nothing (originally I had it equal to 0 but that broke my code as sometime it is a negative number), then I had a conditional checking if the current sum (from the reduce) was greater than the maxSum (or if maxSum was undefined for the first iteration), and if sum was greater replace maxSum with the current sum. And as the final return before the function closed out I returned maxSum. I knew I could have wrapped the entire loop (instead of the for loop) in a filter, but I felt the code was less readable to I kept it in a for loop.

What I learned from other people’s code:

Some people really love to concise everything down to one line. And I really thought it was amazing. But I think I would rather keep my code readable, so when I came back to it after some time, I would be able to understand it quite quickly. Some mapped it into an array (instead of my outer for loop) and called Map.max on the map, that is cool 🙂 Slice and reduce was used in most, so I’m feeling happy with my code.

Half way through! See you tomorrow!

Day 14 of 30 of Codewars – Javascript

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/reverse-words/javascript

Time: 15 minutes

What I’ve learnt: So this was a relatively easy kata, something I have done before. And I put in my solution and it wouldn’t pass, and was quite confused for a few minutes, until I realized there were no initial tests and I had to create them! So I used Test.assertEquals(functionToBeCalled, ExpectedReturn, ‘Description of test’). I used a map here, and joined them right back to be a string after my map, instead adding to a variable holding through the string as it loops.

Here was my solution:

1
2
3
function reverseWords(str) {
  return str.split(" ").map((word)=> {return word.split("").reverse().join("")}).join(" ")
}

 

What I learned from other people’s code:

I think most people did almost identical to mine. In fact there are 328 grouped as having done the kata like that. Someone others split the whole thing without space (by letters), reversed everything, then joined back together, split again by space and then did one more reverse to put the words back in order. That is definitely an out of the box way to think about such a problem.

I hope my javascript is improving! Until tomorrow 👋

 

Day 13 of 30 of Codewars – Javascript

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/deep-freeze/javascript

Time: 30 minutes

What I’ve learnt: So we had to freeze the first object and then the inner ones, so recursion was definitely called for. I used the javascript for in loop which is a nice change from the regular for loop which would not have worked well here. I got confused first trying to check if the item was an object, until I realized I needed to check the value of the object itself, and not the item alone (object[item]).  That’s what took me the longest time. I also tried to make it more concise after with reduce or map, but it really wasn’t necessary or cleaner, so left as is.

Here was my solution:

1
2
3
4
5
6
Object.deepFreeze = function (object) {
  Object.freeze(object)
  for (var property in object) {
    if (object[property] instanceof Object) Object.deepFreeze(object[property])
  }
}

What I learned from other people’s code:

Seems like recursion was common practice here. typeof is another way to check for an object as opposed to instanceOf Object. Happy to see no one used reduce or filter. 😉

Can’t wait for tomorrow’s challenge 🙂

Day 12 of 30 of Codewars – Javascript

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/dont-rely-on-luck/javascript

Time: 8 minutes

What I’ve learnt: It took me about a minute to realize that we need to override a javascript built in function here. And about 7 minutes to realize exactly how to do this. I tried first by recreating the function, but I was getting an error creating a function with the name Math.floor, and then I tried assigning it to a variable with a const, and then realized that won’t work because it has already been created! So I just did Math.floor = and that worked the magic!

Here was my solution:

1
2
3
4
5
var guess = "Sorry. Unlucky this time."

Math.floor = () => {
  return "Sorry. Unlucky this time."
}

 

What I learned from other people’s code:

Well, everyone did this quite similarly, there is not much change you can do. I guess I could have put my arrow function on one line to knock down some of the lines of code, and the return.  I also did not realize that you just had to have a static return, and that it did not need to return that particular string.

And, onto the next!

Day 11 of 30 of Codewars – Javascript

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/find-the-divisors/solutions/javascript

Time: 20 minutes

What I’ve learnt: This was pretty straightforward code-wise. I started my for loop though at 2 because 0 and 1 are not something I would need to check for to see if a number has divisors. And we only need to check until the integer/2, instead of the entire integer.

Here was my solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function divisors(integer) {
  const divisors = []
  
  for (let i = 2; i <= integer /2; i++) {
    if (integer % i === 0) {
      divisors.push(i)
    }
  }
  return divisors.length ? divisors : `${integer} is prime`
};

 

What I learned from other people’s code: I feel like some people tried to shove their code together to take up less lines, but it made it much less readable. Overall seems everyone did similar.  No new fancy javascript syntax on this one!

See you tomorrow!

Day 10 of 30 of Codewars – Javascript

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/5839edaa6754d6fec10000a2

Time: 25 minutes

What I’ve learnt: This one I did in my weekly javascript study group with a few coding buddies. I love doing kata together as we get to discuss different ideas together 🙂

We used functions we have all used in the past to achieve this solution, inside our for loop. Nothing too new this time.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function findMissingLetter(array) {
  let nextLetter = 0;
  
  for (let i = 0; i < array.length - 1; i++) {
    let currentLetter = array[i].toLowerCase().charCodeAt();
    nextLetter = array[i + 1].toLowerCase().charCodeAt();
      
    if (nextLetter && nextLetter !== currentLetter + 1) {
      return String.fromCharCode(array[i].charCodeAt() + 1 )
    }
  }
}

 

What I learned from other people’s code:
Although not required from the kata, I like it how someone used

throw new Error(“Invalid input”)

The sound of that function totally matches what it does! It’s awesome!

Otherwise I feel people have reached their solution similarly to ours. I do like MaximumJoe’s one line solution using reduce. Gotta start reducing too!

Until tomorrow!

Day 9 of 30 of Codewars – Javascript

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/find-the-parity-outlier/

Time: 25 minutes

What I’ve learnt: So I made an inner function isEven to keep my code a bit DRYer, as this is something I am checking over and over. I’ve used quite a large condition for my ternary for integersType, but I think it does the job. 🙂

Here was my solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
function findOutlier(integers){

  function isEven(num){
    return num % 2 === 0
  }
  
  let integersType
  (isEven(integers[0]) && isEven(integers[1])) || 
  (isEven(integers[1]) && isEven(integers[2])) || 
  (isEven(integers[0]) && isEven(integers[2])) ? integersType = "even" : integersType = "odd"
  
  for (let i = 0; i < integers.length; i++){
    if (integersType === "even" && !isEven(integers[i]) ){
      return integers[i] 
    } else if (integersType === "odd" && isEven(integers[i])){
      return integers[i] 
    }
  }
}

 

What I learned from other people’s code:

Interesting how people used filter to gather all the even and odd numbers separately, and see which one had only one number, and return that. So although I know how to use filter and reduce, I don’t use it often enough.

Another day of learning, a better programmer 🙂

Day 7 of 30 of Codewars – Javascript

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!

Day 6 of 30 of Codewars – Javascript

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/human-readable-time/javascript

Time: 20 minutes

What I’ve learnt: So I know I could have done this with less conditions, but I was more focused today in trying to accomplish this in a timely way. So there was a lot of copy and paste code, just using a bit different math. Maybe I could have created an outer function I could have passed the math into to keep my code DRYer. I’m never sure how much I should be doing to keep these kata cleaner and cleaner. For now focusing on getting through the challenges in a timely way.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
function humanReadable(seconds) {
  const time = {hours: "00", minutes: "00", seconds: "00"}
  function convertSeconds(seconds){
    if(seconds < 60){
      if (seconds < 10) time.seconds = `0${seconds}`
      else time.seconds = seconds
    } else if(seconds < 3600){
      const minutes = Math.floor(parseInt(seconds)/60)
      if (minutes < 10) time.minutes = `0${minutes}`
      else time.minutes = minutes
      convertSeconds(parseInt(seconds) % 60)
    } else {
      const hours = Math.floor(parseInt(seconds)/3600)
      if (hours < 10) time.hours = `0${hours}`
      else time.hours = hours
      convertSeconds(parseInt(seconds) % 3600)
    }
  }
  convertSeconds(seconds)
  return `${time.hours}:${time.minutes}:${time.seconds}`
}

What I learned from other people’s code: OK, so I see people have created that inner function to call 3 times, and did so very elegantly! Than they returned the function call interpolated with the : Truly concise and impressive! Hmm. So maybe I should spend more time refactoring my code. Although I do see that 31 people did that together!! Power of the pairing 🙂

I do see someone here using =~~. I’ve never seen this, and not sure how to look this one up since google is not really allowing me to search for it. Will ask some of my friends what they think!

Have a good one!

Copyright Loving to Code 2025
Tech Nerd theme designed by Siteturner