i'm constructing javascript function takes single-lined string of text , length variable expected justification width (longest word never exceed width). here more requirements:
- use spaces fill in gaps between words
- each line needs contain many words can fit within length given.
- use
\n
(newline) separate lines (not included in line length count) - gap between words can't differ more 1 space
- lines need end word , not space
- space gaps go larger smaller across line.
- last line not justification (single spacing only) , cannot have
\n
- strings 1 word need no space padding.
with no further ado, here's code:
var justify = function(str, len) { var re = regexp("(?:\\s|^)(.{1," + len + "})(?=\\s|$)", "g"); var res = []; var finalresult = []; while ((m = re.exec(str)) !== null) { res.push(m[1]); } var lastline = res.pop(); (var = 0; < res.length; i++) { var linelength = res[i].length; if (linelength !== len) { var toadd = len - linelength; var indexof = res[i].indexof(' ', 0); var str2 = res[i]; if ( indexof === -1 ) { str2; } while ( indexof > -1 ) { str2 = str2.substring(0, indexof + 1) + " " + str2.substring(indexof + 1); if ( str2.length < len ) { indexof = str2.indexof(' ', (indexof + 1)); } else { break; } } finalresult.push(str2); } } finalresult.push(lastline); return finalresult.join('\n'); }
i'm using regexp carve out strings of or under proscribed line length (len
) , return each line element in new array. last line removed array via pop
, saved variable future use on finished array. utilize loop iterate on line array , find out needs added line length len
length. split out each individual line according existing spaces (via .substring method) , add spaces spaces pad out lines needed.
unfortunately, code not passing tests receive error messages indicating total number of lines less what's expected. (i.e. line count not equal 44 - expected: 44, instead got: 40
).
i've noticed results violate 1 of code requirements (gaps between words must not differ more 1 space). example, 1 of line justifies follows (spaces represented colons :
nisi::::volutpat:ac.
how can distribute spacing more appropriately? believe need iterate on spaces, attempted iteration isn't working intended. i'm assuming once that's resolved, error line count discrepancy clear up. thank tips or help.
Comments
Post a Comment