Skip to content

Instantly share code, notes, and snippets.

@TobiahRex
Created January 28, 2019 18:09
Show Gist options
  • Save TobiahRex/fbc25cab187702328ea977473aef0f8c to your computer and use it in GitHub Desktop.
Save TobiahRex/fbc25cab187702328ea977473aef0f8c to your computer and use it in GitHub Desktop.
Recursive Algo for word wrapping, given a fixed div width.
/* eslint-disable */
let result = '';
let test = "tobiah is happy eandhelovestocode fordaysanddaysanddays";
[
'tobiah',
'is',
'happy',
'eandhelovestocode',
'fordaysanddaysanddays'
]
[ 'tobiah is happy',
'eandhelovestocode',
'fordaysanddaysanddays' ]
const formatWords = (i, oldWords, newWords = []) => {
if (i === oldWords.length) return;
const lastWord = newWords[newWords.length - 1] || '';
const nextWord = oldWords[i += 1] || '';
if ((lastWord.length + nextWord.length + 1) < 19) {
newWords.push(`${nextWord} `);
} else {
newWords.pop();
newWords.push(`${lastWord}\n`);
newWords.push(nextWord);
}
formatWords(i, oldWords, newWords);
return newWords.join('');
}
result = formatWords(-1, test.split(' '));
console.log(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment