Created
January 28, 2019 18:09
-
-
Save TobiahRex/fbc25cab187702328ea977473aef0f8c to your computer and use it in GitHub Desktop.
Recursive Algo for word wrapping, given a fixed div width.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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