Intro ๐
Problem solving is an important skill, for your career and your life in general.
That's why I take interesting katas of all levels, customize them and explain how to solve them.
Understanding the Exerciseโ
First, we need to understand the exercise!
If you don't understand it, you can't solve it!.
My personal method:
- Input: What do I put in?
- Output: What do I want to get out?
Today's exercise
Source: Codewars
Today as small kata with a little bit of historical background about Sigmund Freud.
Write a function toFreud
, that accepts one parameter: myString
.
Given a string, e.g. "Sigmund Freud"
,
return the string with every word replaced by the word "sex"
, e.g. "sex sex"
.
An empty string or no argument should result in an empty string.
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:
- Return an empty string if string is empty or no argument
- Loop over every word of the string
- Replace each word with
"sex"
- Return a string of all new words
Example:
- Input:
"Sigmund Freud"
- Return an empty string if string is empty or no argument:
false
- Iteration 1: "Sigmund" => replace it =>
"sex"
- Iteration 2: "Freud" => replace it =>
"sex"
- Return a string of all new words:
"sex sex"
- Output:
"sex sex"
โ
Implementation (functional) โ
function toFreud(myString) {
return !myString
? "" // return an empty string if string is empty or no argument
: myString
.split(" ") // split string into words
.map((word) => "sex") // replace each word with `"sex"`
.join(" "); // put replaced words together
}
Result
console.log(toFreud("Sigmund Freud"));
// "sex sex" โ
console.log(toFreud(""));
// "" โ
Implementation (regex) โ
function toFreudRegex(myString) {
return !myString
? ""
: myString.replace(/\S+/g, "sex"); // find all places that have "one or more non-white space", replace them with "sex"
}
The regex \S
character class "matches a single character other than white space". You can read about it here.
The regex +
quantifier "matches the preceding item 1 or more times". You can read about it here.
Result
console.log(toFreud("Sigmund Freud"));
// "sex sex" โ
console.log(toFreud(""));
// "" โ
Playground โฝ
You can play around with the code here
Next Part โก๏ธ
Great work!
We learned how to use split
, map
, join
, replace
and some regex.
I hope 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!
Further Reading ๐
Questions โ
- How often do you do katas?
- Which implementation do you like more? Why?
- Any alternative solution?
Top comments (1)
This is actually funny. ๐