Message from JavaScript discussions
July 2017
— Decided on this regex:var segmentRegex = '.{1,' + maxLen + '}(\\s|$)';
function wordWrap(input, maxLen, wordSep = ' ', lineDelim = '\n') {
if (
typeof input !== 'string' ||
input.length < maxLen
) {
return input;
}
const lines = [];
const lastLine = input.split(wordSep).reduce((line, word) => {
line.push(word);
if (line.join(wordSep).length > maxLen) {
const next = line.pop(word);
lines.push(line);
return [ next ];
}
return line;
}, []);
if (lastLine.length > 0) {
lines.push(lastLine);
}
return lines.map(line => line.join(wordSep)).join(lineDelim);
}
— Working solution
— Goddamn, it was a bit complex
— Added two optional args as well
— Haha, yeah that's about what you get on Google results
— Oh.. kek
— But this is better imo
— Maybe
— I realized half the regex was useless
— Can you perftest? :P
— I pass the unit tests either way