DEV Community

Cover image for JavaScript Katas: Split In Parts
miku86
miku86

Posted on

JavaScript Katas: Split In Parts

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

Today, another 7 kyu kata,
meaning we slightly increase the difficulty.

Source: Codewars

Write a function splitInParts, that accepts two parameters: myString and partLength.

Given a string, e.g. "HelloDev",
and a number, e.g. 3,
return the input string split into partLength-long parts separated by a space, e.g. Hel loD ev.


Input: a string and a number.

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:

  1. Get a partLength-long part of the input string and add a space
  2. Do this for every part
  3. Add the remaining part to the end
  4. Return the string

Example:

  • Input: "HelloDev", 3
  • Get a 3-long part of the input string and add a space: "Hel "
  • Get a 3-long part of the input string and add a space: "loD "
  • Add the remaining part to the end: "ev"
  • Return the string: "Hel loD ev"
  • Output: "Hel loD ev"

Implementation ⛑

function splitInParts(myString, partLength) {
  let remaining = myString;
  let result = "";

  // do it only if the remaining string is longer than the parts
  while (remaining.length >= partLength) {
    // add the next part and a space to the result
    result += remaining.slice(0, partLength) + " ";

    // remove the added part from the remaining string
    remaining = remaining.slice(partLength);
  }

  // add the last part that was smaller than the part length
  result += remaining;

  // remove a trailing space
  return result.trim();
}
Enter fullscreen mode Exit fullscreen mode

Result

console.log(splitInParts("HelloDev", 3));
// "Hel loD ev" ✅

console.log(splitInParts("HelloDev", 1));
// "H e l l o D e v" ✅
Enter fullscreen mode Exit fullscreen mode

Playground ⚽

You can play around with the code here


Next Part ➡️

Great work!

We learned how to use while, slice, trim.

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?

Latest comments (4)

Collapse
 
gerges27 profile image
Gerges Nady

let splitInParts = (myString, partLength) => {
let res = ""
let count = 0

for (let i = 0; i < myString.length; i += partLength) {
    for (let j = i; j < (partLength + count); j++) {
        if (myString[j] !== undefined) {
            res += myString[j]
        }
    }
    count = (count + partLength)
    res += " "
}
console.log(res)
Enter fullscreen mode Exit fullscreen mode

}

Collapse
 
westim profile image
Tim West • Edited

Another golf-style solution that doesn't abuse regular expressions 😎

const splitInParts = (s, l) => {
    s.split('').map((c,i) => (i+1) % l ? c : `${c} `).join('').trim();
}

Here's the less abusive solution I would actually use:

const splitInParts = (s, partLength) => {
    const result = [];

    for (let start = 0; start < s.length; start += partLength)
        result.push(s.slice(start, start + partLength));

    return result.join(' ');
}

This works because String.prototype.slice() will stop at the end of the string if the second argument index is out of bounds.

Collapse
 
nibble profile image
Joseph Mawa

Another possible solution.

function splitInParts(myString, partLength) {
  let ans = "",
    i = 0;
  while (i < myString.length) {
    ans += myString.slice(i, i + partLength) + " ";
    i += partLength;
  }
  return ans.slice(0, -1);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kosich profile image
Kostia Palchyk • Edited

Okay, this one is easy enough for me..

const splitInParts =
  (s, n) => s.replace(new RegExp(`.{${n}}`, 'g'), '$& ')