JavaScript Katas: Count the number of characters in a string

Intro 🌐

I take interesting katas of all levels and explain how to solve them.

Problem solving is an important skill, for your career and your life in general.

You'd better learn to solve problems!


Source

I take the ideas for the katas from different sources and re-write them.

Today's source: Codewars


Understanding the Exercise ❗

First, we need to understand the exercise!

This is a crucial part of (software) engineering.

Go over the exercise explanation again until you understand it 100%.

Do NOT try to save time here.

My method to do this:

  1. Input: What do I put in?
  2. Output: What do I want to get out?

Today's exercise

Write a function countAmountOfEachCharacter, that accepts one parameter: inputString, a valid string.

The function should return an object. The object has a key for every character that exists at least once in the string. The value for each key is how many times that character exists in the string.


Input: a string.

Output: an object with keys for the existing characters and values for how many times that character exists in the string.


Thinking about the Solution 💭

I think I understand the exercise (= what I put into the function and what I want to get out of it).

Now, I need the specific steps to get from input to output.

I try to do this in small baby steps.

  • loop over the input string
  • if the character never has been seen before, add it to the object with a count of 1
  • if the character has been seen before, increase its count by 1
  • return the object with every key-value pair

Example:

  • Input: "bee"
  • Round 1: { "b": 1 } // next character is "b", which has never been seen before, therefore add it to the object with a count of 1
  • Round 2: { "b": 1, "e": 1 } // next character is "e", which has never been seen before, therefore add it to the object with a count of 1
  • Round 3: { "b": 1, "e": 2 } // next character is "e", which HAS been seen before, therefore increase its count by 1
  • Output: { "b": 1, "e": 2 } // return the object with every key-value pair

Implementation (for loop) ⛑

function countAmountOfEachCharacter(inputString) {
  const returnObject = {};

  // loop over input string
  for (let i = 0; i < inputString.length; i++) {
    // check if character has been seen before
    if (returnObject.hasOwnProperty(inputString[i])) {
      // increase its count by 1
      returnObject[inputString[i]] += 1;
    } else {
      // add it to the object with a count of 1
      returnObject[inputString[i]] = 1;
    }
  }

  return returnObject;
}

Result

console.log(countAmountOfEachCharacter("bee"));
// { b: 1, e: 2 }

console.log(countAmountOfEachCharacter("mississippi"));
// { m: 1, i: 4, s: 4, p: 2 }

Warning

If you use emojis in your string, you should avoid the normal for-loop.

Thanks to Benito van der Zander for commenting!


Implementation (for of-loop) ⛑

function countAmountOfEachCharacter(inputString) {
  const returnObject = {};

  // loop over input string
  for (const character of inputString) {
    // check if character has been seen before
    if (returnObject.hasOwnProperty(character)) {
      // increase its count by 1
      returnObject[character] += 1;
    } else {
      // add it to the object with a count of 1
      returnObject[character] = 1;
    }
  }

  return returnObject;
}

Result

console.log(countAmountOfEachCharacter("bee"));
// { b: 1, e: 2 }

console.log(countAmountOfEachCharacter("mississippi"));
// { m: 1, i: 4, s: 4, p: 2 }

Implementation (Functional) ⛑

function countAmountOfEachCharacter(inputString) {
  // convert the string to an array
  return [...inputString].reduce(
    (accumulated, currentChar) =>
      // check if character has been seen before
      accumulated.hasOwnProperty(currentChar)
        ? { ...accumulated, [currentChar]: accumulated[currentChar] + 1 } // increase its count by 1
        : { ...accumulated, [currentChar]: 1 }, // add it to the object with a count of 1
    {} // start with an empty object
  );
}

Result

console.log(countAmountOfEachCharacter("bee"));
// { b: 1, e: 2 }

console.log(countAmountOfEachCharacter("mississippi"));
// { m: 1, i: 4, s: 4, p: 2 }

Playground ⚽

You can play around with the code here


Next Part ➡️

Great work, mate!

Next time, we'll solve the next kata. Stay tuned!

If I should solve a specific kata, shoot me a message here.

If you want to read my latest stuff, get in touch with me!


Further Reading 📖


Questions ❔

  • Do you like to solve katas?
  • Which implementation do you like more? Why?
  • Any alternative solution?