Skip to content

Instantly share code, notes, and snippets.

@moserrya
Last active December 16, 2015 10:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moserrya/5423850 to your computer and use it in GitHub Desktop.
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.
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
};
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