DEV Community

Discussion on: JavaScript Katas: Split In Parts

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.