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
Write a function sortAndStar
, that accepts one parameter: stringArray
.
Given an array, e.g. ["We", "solve", "Katas"]
,
sort it alphabetically (case-sensitive) and return the first string of the sorted array,
with all characters separated by ***
between each other, e.g. "K***a***t***a***s"
.
Input: an array of strings.
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:
- Sort the array (case-sensitive)
- Take the first array element
- Put
***
between each char
Example:
- Input:
["We", "solve", "Katas"]
- Sort array:
["Katas", "We", "solve"]
(case-sensitive) - Take first array element:
"Katas"
- Put
***
between each char:"K***a***t***a***s"
- Output:
"K***a***t***a***s"
β
Implementation β
function sortAndStar(stringArray) {
const sorted = stringArray.sort(); // the default sort function works
return sorted[0] // take first element
.split("") // split string into chars
.join("***"); // join chars with ***
}
Result
console.log(sortAndStar(["We", "solve", "Katas"]));
// "K***a***t***a***s" β
Playground β½
You can play around with the code here
Next Part β‘οΈ
Great work!
We learned how to use sort
, split
and join
.
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?