BRB... Joining Codewars Anonymous

Photo by Rosie Sun on Unsplash

BRB... Joining Codewars Anonymous

And my favorite code snippet

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?