Last active
March 4, 2021 15:20
-
-
Save formix/29e4dcbefb17403e53b3 to your computer and use it in GitHub Desktop.
JavaScript Word Wrap
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
/** | |
* Wrap text to a maximum of 78 char per line. Indent the text using the number | |
* of spaces specified by indent. | |
*/ | |
function wrap(text, indent) { | |
if (!text) { | |
console.log(); | |
return; | |
} | |
var col = 0; | |
var words = text.split(/ /g); | |
var firstWord = true; | |
for (var i = 0; i < words.length; i++) { | |
if (col == 0) { | |
firstWord = true; | |
if (indent) { | |
for (var j = 0; j < indent; j++) { | |
process.stdout.write(" "); | |
col++; | |
} | |
} | |
} | |
var word = words[i]; | |
if ((col + word.length) > 78) { | |
console.log(); | |
col = 0; | |
i--; | |
} else { | |
if (!firstWord) { | |
process.stdout.write(" "); | |
col++; | |
} | |
process.stdout.write(word); | |
col += word.length; | |
firstWord = false; | |
} | |
} | |
console.log(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment