Last active
December 16, 2015 10:58
-
-
Save moserrya/5423850 to your computer and use it in GitHub Desktop.
Justify strings to a given width. Works in-place without breaking the string into an array.
This file contains 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
function justify(str, width) { | |
var whitespace = ' '; | |
while (str.length < width) { | |
var oldLength = str.length; | |
var spacing = new RegExp("(\\w)" + whitespace + "(\\w)"); | |
str = str.replace(spacing, '$1 ' + whitespace + '$2'); | |
if (oldLength === str.length) { | |
whitespace += ' '; | |
} | |
} | |
return str | |
}; |
This file contains 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
def justify!(str, width) | |
whitespace = ' ' | |
while str.length < width | |
spacing = Regexp.new("(\\w)#{whitespace}(\\w)") | |
sub = str.sub!(spacing, "\\1 #{whitespace}\\2") | |
whitespace << ' ' unless sub | |
end | |
str | |
end | |
def justify(str, width) | |
justify!(str.dup, width) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment