DEV Community

Cover image for JavaScript Katas: Count the number of each character in a string
miku86
miku86

Posted on • Updated on

JavaScript Katas: Count the number of each character 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;
}
Enter fullscreen mode Exit fullscreen mode

Result

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

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

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;
}
Enter fullscreen mode Exit fullscreen mode

Result

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

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

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
  );
}
Enter fullscreen mode Exit fullscreen mode

Result

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

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

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?

Top comments (9)

Collapse
 
theonlybeardedbeast profile image
TheOnlyBeardedBeast

Here is my reduce solution

const result = text.split("").reduce((acc,val)=>{
  acc[val]=(acc[val]||0)+1;
  return acc;
},{})
Collapse
 
jonrandy profile image
Jon Randy 🎖️

Shorter version:

const result = [...text].reduce(
  (acc,val)=>(acc[val]=~~acc[val]+1,acc), {}
)
Collapse
 
theonlybeardedbeast profile image
TheOnlyBeardedBeast

Nice!

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Golfed. Can anyone go smaller? 😛

let c=t=>[...t].reduce((a,v)=>(a[v]=~~a[v]+1,a),{})
Collapse
 
miku86 profile image
miku86

Hey Jon,

we can remove the let 😜

Collapse
 
benibela profile image
Benito van der Zander

Careful, the first for-loop does not work with emojis

Collapse
 
miku86 profile image
miku86

Hey Benito,

thanks for your answer!
Can you tell me which emojis you tested?

I added a test case to my playground and it seems to work.

Greetings
Michael

Collapse
 
benibela profile image
Benito van der Zander

just the first one I found 🤔

Thread Thread
 
miku86 profile image
miku86 • Edited

Alright!
I tried some different ones and found some, that result in a question mark.

So I researched the problem:

I just updated the post, thank you!