โ† Blog

JavaScript Katas: Count the number of characters in a string

July, 2020

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?

miku86

Hi! I'm Michael ๐Ÿ‘‹ I'm a Mentor & Educator & Senior Web Developer - I help you to reach your (career) goals.