Created
November 20, 2012 02:13
-
-
Save vincentmac/4115504 to your computer and use it in GitHub Desktop.
JS wordwrap
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
// Vincent Mac | |
// coded up answer to what John had asked me. | |
// Wrapped in anonymous function to prevent polution of global namespace. | |
(function() { | |
"use strict"; | |
var maxWidth = 50; // desired column width in number of characters | |
var paragraph = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; | |
// var paragraph = "one two three four five six seven eight nine ten"; | |
/** | |
* function to typeset a `paragraph` to a given column `maxWidth` | |
* | |
* @param {String} paragraph | |
* @param {Number} maxWidth | |
* | |
* @return {Boolean} | |
*/ | |
function wrapParagraph(paragraph, maxWidth) { | |
var strBuffer = ''; | |
var words = []; | |
words = paragraph.split(' '); // split paragraph into an ordered array | |
function isStringTooLong(strBuffer) { | |
// Alternate methods could include actually calculating the pixel width for | |
// use with non-monospaced fonts. This would require a parameter for font size. | |
if (strBuffer.length > maxWidth) { | |
return true; | |
} | |
return false; | |
} | |
for (var i = 0; i < words.length; i++) { | |
var word = words[i]; | |
if (isStringTooLong(strBuffer + word)) { | |
// write output to screen and then reset strBuffer with new word | |
console.log(strBuffer); | |
strBuffer = word + ' '; | |
} else { | |
strBuffer += word + ' '; // add word to string buffer | |
} | |
} | |
console.log(strBuffer); // display trailing content | |
} | |
wrapParagraph(paragraph, maxWidth); | |
return null; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment