Created
November 13, 2015 15:57
-
-
Save christopherhill/3d2766c25c952367c83e to your computer and use it in GitHub Desktop.
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
'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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Quick and dirty text justification example in Javascript.