christopherhill
11/13/2015 - 3:57 PM

gistfile1.txt

'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);