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?
Top comments (4)
Let's avoid destroying our inputs.
And let's decompose it into vaguely sensible operations.
Nice work,
I like it!
Hey Jon,
thanks for your solution!
So instead of using
split, we convert the string into a new array by spreading it.