BRB... Joining Codewars Anonymous

Hattie TavaresHattie Tavares
2 min read

I have an addiction. Codewars has it's hooks in me. I have to purposely limit the number I do each day or I'd probably spend all day (and night) doing them. I've always loved puzzles and figuring things out, and doing katas just gives me that hit of excitement that comes from solving something.

So it seems right that I should share my favorite bit of code to solve things. It's probably the thing I've used most (besides maybe for loops).

let dict = {}
   for (const item of array) {
    if (dict[item]) {
      dict[item]++
    } else {
      dict[item] = 1
    }
 }

I have used this so many times and for so many reasons. To break it down, this code creates an object that iterates through an array and checks each item to see if it's already in the object. If it is, it increments the value by 1, otherwise it adds the item and gives it a value of one.

There are a ton of katas asking you to find the counts of all characters in a string, the only character in a string that appears only once, or which is the only one to appear more than once. And with the dict object, you can find, filter (use Object.keys or Object.values to create a new array), map strings to their values and more. You can also modify this to change what the key:value pairs hold, like the index of the item instead of the number of times it appears.

So that's my current favorite code snippet. Do you have one?

6
Subscribe to my newsletter

Read articles from Hattie Tavares directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Hattie Tavares
Hattie Tavares

I have always had an interest in tech and computers. I initially went to college for Web Design before becoming the primary caretaker for both my own 3 children and 3 others. Then in 2020 when the pandemic intensified and my caretaking demands slowed, I decided to double down on my love for tech, refreshing my skills and learning to program. The pandemic had really highlighted the lack of resources available to parents who suddenly needed to homeschool. I was inspired to create an app called Homeschool Dash, to help caretakers track and manage students' grades. While building this app I realized how much I enjoyed being able to use my skills to help solve an important problem.