Day 20 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/moving-zeros-to-the-end/

Time: 10 minutes

What I’ve learnt: So this was a 5KYU and labeled as an interview question. It didn’t look that difficult, but I thought it must be harder. Happy to say, I must be improving because it was not very hard.

I took the array we were given in, and filtered this based on values !== 0and assigned this to a variable to use later on. Then I created a for loop to iterate as many times as the difference in length between the original array, to the newly filtered array, and passed in 0 to a newly created array assigned to it’s own variable.

And then I returned the two arrays combined with the spread operator `return […newArray, …zeroArray]`

What I learned from other people’s code: Ok, so silly me, I didn’t need a for loop for the 0’s, I could have just used two filters, one for everything but 0’s and then one for only 0’s and concatenated these two all in one line! But more or less the same idea!  I thought someone would do something with regex, but I didn’t see any.

See you tomorrow!

Day 19 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/counting-duplicates/javascript

Time: 10 minutes

What I’ve learnt: First things first I made all letters lowercase, and split it into an array of sorted letters. I wanted to use a reduce, and decided I needed to keep track of the previous letter, as well as letters that were already marked duplicate, because I need to make sure not to duplicates multiple time on the same letter. So I passed in the initial value of the reduce to look like `{prevLetter: “”, dupsArray: []}`.

Then in each iteration of the reduce I checked if the previous letter was equal to the accumulator.prevLetter && that it was not included in the accumulator.dupsArray, if both these conditions were met I added it to the accumulator.dupsArray. Then I reset the prevLetter to the currentLetter,  and returned the new accumulator.

Once this finished I just needed to return the reduce.dupsArray.length. All done 🙂

What I learned from other people’s code: It is interesting how people used regex to check for dups. `match(/([^])\1+/g)` I’ll have to play with that on a regex site!

And onto the next 🙂

Day 18 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/sum-of-a-nested-list/javascript

Time: 60 minutes

What I’ve learnt: So I spent time doing this one (even though it is a kata 7, it took me a while because I wanted to do it without too many conditionals. After some trial and error of trying to create a reduce method that would flatten the array (which on some conditions would need to have been done recursively because they were nested), I decided to simple join the array into a string.

This gave me a string with commas, so I just ignored the commas with a match using some regex. Yay!! I finally used regex! Match returned me an array of numbers so I can reduce it down to it’s sum. I needed to add in a ternary to check if the array converted to a string without commas was undefined , because otherwise calling reduce on that would fail.

What I learned from other people’s code: I saw a lot of recursion, where in their reduce they checked if Array.isArray, and then if it was they did recursion on that array to the entire method, which built up a stack for the reduce to sum up. And someone used lodash _flatten!

Have a good one!

Day 17 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/string-array-revisal/javascript

Time: 30 minutes

What I’ve learnt: This was done at my weekly javascript meet-up. Thanks for everyone’s awesome ideas! So again, string manipulation. I will expect to see regex in the solution. 🙂 But at this meeting, we were using our more comfortable conditionals. Pretty standard manipulation, and adding onto a string within a for loop to get this kata solved.

Here was my solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function dup(stringArray) {
  let result = [];
  for (let i = 0; i < stringArray.length; i++) {
    let previousLetter;
    let newStrings = stringArray[i].split('')
    
    newStrings.forEach(letter=> {
      if (!previousLetter) {
        result[i] = letter;
      } else if (letter !== previousLetter) { 
        result[i] += letter;
      } 
      previousLetter = letter;
    })
  }
  return result;
};

 

What I learned from other people’s code:

So as I expected, I see some replace with regex 🙂 This is definitely something we are going to have to do at a future meet-up. It’s amazing how they can conquer so much, in so little code. But until I start playing with it more it feels so untouchable! Add to the TODO: regex!!

Have a good night all 🙂

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!

Copyright Loving to Code 2025
Tech Nerd theme designed by Siteturner