← Blog

JavaScript Katas: Abbreviate a two word name

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 abbreviateName, that accepts one parameter: name.

name is a string that includes two words, with one space in between them, e.g. “John Doe”.

The output should be the two first characters, both capitalized with a dot separating them, e.g. “J.D”.

"John Doe" => "J.D"

"john doe" => "J.D"


Input: a string.

Output: a 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.

  1. split the name into two words
  2. take the first character of the word
  3. capitalize this character
  4. do this for both words
  5. join both characters with a dot
  6. return the joined characters

Example:

  • Input: "john doe"
  • Split them: ["john", "doe"]
  • Take 1st char: "j" // 1st word
  • Capitalize it: "J" // 1st word
  • Take 1st char: "d" // 2nd word
  • Capitalize it: "D" // 2nd word
  • Join them with a dot: "J.D"
  • Output: "J.D"

Implementation (functional) ⛑

function abbreviateName(name) {
  return (
    name
      // split the name into two words
      .split(" ")

      // take first char of both parts and capitalize them
      .map((part) => part[0].toUpperCase())

      // join both characters with a dot
      .join(".")
  );
}

Result

console.log(abbreviateName("John Doe"));
// J.D

console.log(abbreviateName("john doe"));
// J.D

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.