I'm working on a challenge that asks to insert new line characters at specific intervals in a string. Examples of expected returns:
insertNewLine('Happiness takes wisdom and courage', 20) => 'Happiness takes\nwisdom and courage'
insertNewLine('Happiness takes wisdom and courage', 30) => 'Happiness takes wisdom and\ncourage'
So far I've been thinking that an easy algorithm to implement would be this:
- split the string into equal chunks, passed on the desired width
- find the last index of space in each chunk and replace it with \n
Clearly the algorithm is flawed because this is the return I'm getting, mainly because I'm looping over the array of string chunks and always adding a newline char in each chunk. This is the correct output:
insertNewLine('Happiness takes wisdom and courage', 20) => 'Happiness takes\nwisdom and\ncourage'
What would be a better algorithm to achieve the expected results?
Here's the code too:
const _ = require('underscore')
const insertNewLine = (text, width) => {
if (width < 15) return 'INVALID INPUT';
if (text.length <= width) return text;
else {
const arrayOfText = text.split('');
const temparray = [];
for (let i = 0; i < arrayOfText.length; i += width) {
temparray.push(arrayOfText.slice(i, i + width));
}
return temparray.map((elem, i, arr) => {
elem[_.lastIndexOf(elem, ' ')] = '\n';
return elem.join('');
}).join('');
}
};