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:
- Input: What do I put in?
- 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.
- split the name into two words
- take the first character of the word
- capitalize this character
- do this for both words
- join both characters with a dot
- 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?
Top comments (1)
Improved version: