Skip to content

Instantly share code, notes, and snippets.

@christopherhill
Created November 13, 2015 15:57
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 christopherhill/3d2766c25c952367c83e to your computer and use it in GitHub Desktop.
Save christopherhill/3d2766c25c952367c83e to your computer and use it in GitHub Desktop.
'use strict';
function justify(str, lineLength) {
if (str.length >= lineLength) {
throw 'Line length is equal to or exceeds justification length';
}
function genArrayOfSpaces(len) {
var arr = [];
for (var i = 0; i < len; i++) {
arr[i] = ' ';
}
return arr;
}
function genSpaces(num) {
var result = '';
for (var i = 0; i < num; i++) {
result += ' ';
}
return result;
}
var totalChars = str.replace(/ /g,'').length;
var spacesToAdd = lineLength - str.length;
var numGaps = str.length - totalChars;
// the remainder will be added in serial fashion
var extraSpaces = spacesToAdd % numGaps;
var spacesToAddPerGap = (spacesToAdd - extraSpaces) / numGaps;
var extraSpaceStack = genArrayOfSpaces(extraSpaces);
// write the padded string
var justifiedLine = '';
for (var i = 0; i < str.length; i++) {
var thisChar = str.charAt(i);
if (thisChar === ' ') {
justifiedLine += (thisChar + genSpaces(spacesToAddPerGap));
justifiedLine += (extraSpaceStack.pop() || '');
} else {
justifiedLine += thisChar;
}
}
return justifiedLine;
}
function test(expected, result) {
if (expected !== result.length) {
console.log('failed test');
} else {
console.log('test passed: ', result);
}
}
var string = 'The quick brown fox jumps over the lazy dog.';
var lineLength = 103;
var result = justify(string, lineLength);
test(103, result);
@christopherhill
Copy link
Author

Quick and dirty text justification example in Javascript.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment