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 defineSuit
, that accepts one parameter: card
.
Given a card string, e.g. "3β£"
, return a string with the term for the card's suit, e.g. "clubs"
.
Input: a string (a card).
Output: a string (the card's suit)
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.
- create a mapping of the card's suit sign and its suit term
- find the sign of the suit in the string
- find term in the mapping
- return the term of the suit
Example:
- Input:
"3β£"
- Create mapping:
{ "β£": "clubs", "β ": "spades", "β¦": "diamonds", "β₯": "hearts" }
- Find suit sign:
"β£"
- Find term:
"clubs"
- Output:
"clubs"
β
Implementation β
function defineSuit(card) {
// create mapping
const mappingSignToTerm = {
"β£": "clubs",
"β ": "spades",
"β¦": "diamonds",
"β₯": "hearts",
};
// find suit sign (seems to be the last character)
const suitSign = card.slice(-1);
// find term in the mapping
const suitTerm = mappingSignToTerm[suitSign];
// return term
return suitTerm;
}
Result
console.log(defineSuit("3β£"));
// clubs β
console.log(defineSuit("Qβ "));
// spades β
Playground β½
You can play around with the code here
Next Part β‘οΈ
Great work, mate!
I hope, that this was a fairly easy one!
We learned how to use an object for our mapping.
Next time, we'll solve another interesting 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 β
- How often do you do katas?
- Which implementation do you like more? Why?
- Any alternative solution?
Top comments (3)
I like your katas, because I can solve them (well, at least some...)
Makes me feel able as a developer π
Hey Kostia,
thank you, glad you like them!
Do you do katas on a regular base?
Alas, not on a regular basis (just like physical exercises π )
Luckily, I'm following you, so I see and solve a kata once in a while! Thanks for posting em