DEV Community

Cover image for #1 Live Kata Report
Raffaele Pizzari
Raffaele Pizzari

Posted on • Updated on

#1 Live Kata Report

1 Live Kata Report

With the JS Learning community I am running we use to solve "JS Katas" together during "live coding" sessions.
I'll use this blog to share the "Live Kata" reports.

We solved together a "kata" found on "CodeWars.com".

Key takeaway points:

• Learn how Array.prototype.sort() works
• Learn how to write compareFunction for Array.prototype.sort()
• Learn how to match digits in a string with RegEx

Docs:

• A website full of katas
Regex sandbox
Array sort
The Kata is the following:

Requirements:

Your task is to sort a given string.
Each word in the string will contain a single number.
This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.

Example

"is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople"
"" --> ""

Our solutions

Solution 1

function doKata(ex) {
  const arr = ex1.split(' '); 
  const parsedArr = [];

   arr.forEach(function(s) { 
    const index = s.match(/\d/) - 1; 
    parsedArr[index] = s; // parsedArr[1] = "Thi1s";  parsedArr[2] = "is2";  
  });

  return parsedArr.join(' '); // "
}
Enter fullscreen mode Exit fullscreen mode

Solution 2

function doKata(ex) {
  return ex.split(' ').sort(function(a, b) {
    a.match(/\d/) - b.match(/\d/)).join(' ');
  }).join(' ');
}
Enter fullscreen mode Exit fullscreen mode

Thank you all and see you next week :)

About this post

I'm am running a free JavaScript Learning Group on [pixari.slack.com] and I use this blog as official blog of the community.
I pick some of the questions from the #questions-answer channel and answer via blog post. This way my answers will stay indefinitely visible for everyone."

If you want to join the community feel free to click here or contact me:

Oldest comments (0)