β Blog

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 `whoseMove`, that accepts two parameters: `lastPlayer` and `isWin`.

Given a string of the last player, e.g. `"white"`, and a string if s/he won, e.g. `true`, return a string whose turn it is, e.g. `"white"`:

• if the last player has won, then it's his/her turn
• if the last player has lost, then it's the opponent's turn

Input: two strings.

Output: a string.

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. Check if the last player has won
2. If yes (= has won), it's the last player's turn
3. If not (= has lost), it's the opponent's turn
4. Return the string whose turn it is

Example:

• Input: `"white", true`
• Check if the last player has won: `true` => it's the last player's turn
• Output: `"white"` β

Implementation β

``````function whoseMove(lastPlayer, isWin) {
// check if player has won
return isWin
? lastPlayer // if yes, it's the last player's turn
: lastPlayer === "white"
? "black" // if not, and the last player was white, return black
: "white"; // if not, and the last player was black, return white
}``````

Result

``````console.log(whoseMove("white", true));
// "white" β

console.log(whoseMove("black", false));
// "white" β``````

Playground β½

You can play around with the code here

Next Part β‘οΈ

Great work!

We learned how to use the ternary operator.

I hope that you can use your new learnings to solve problems more easily!

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!