miku86

Posted on

JavaScript Katas: Sort and Star

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:

1. Input: What do I put in?
2. 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.

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. Sort the array (case-sensitive)
2. Take the first array element
3. 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!

Questions β

• How often do you do katas?
• Which implementation do you like more? Why?
• Any alternative solution?

pentacular

Let's avoid destroying our inputs.
And let's decompose it into vaguely sensible operations.

``````const sorted = (array) => array.slice().sort();
const starred = (string) => string.split('').join('***');
const sortedAndStarred = (array) => starred(sorted(array)[0]);
``````

miku86

Nice work,
I like it!

Jon Randy ποΈ • Edited
``````const sortAndStar = stringArray=>[...stringArray.sort()[0]].join('***')
``````

miku86

Hey Jon,

So instead of using `split`, we convert the string into a new array by spreading it.