← Blog

JavaScript Katas: Card Suit

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 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.

  1. create a mapping of the card’s suit sign and its suit term
  2. find the sign of the suit in the string
  3. find term in the mapping
  4. 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?

miku86

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