SOURCE

function fullJustify(words,num) {
    const result = [];
    let currentLine = [];
    let currentLength = 0;

    for(const word of words) {
        if(currentLength + word.length + currentLine.length>num) {
            result.push(justifyLine(currentLine,currentLength,num));
            currentLine = [];
            currentLength = 0;
        }
        currentLine.push(word);
        currentLength+=word.length;
    }
    if(currentLine.length>0) {
        result.push(currentLine.join(" ") + " ".repeat(num-currentLength-(currentLine.length-1)));

    }
    return result
}
function justifyLine(lineWords,lineLength,num) {
    if(lineWords.length===1) {
        return lineWords[0] + " " .repeat(num - lineLength);
    }
    const spacesNeeded = num - lineLength;
    const spaceBetweenWords = Math.floor(spacesNeeded/ (lineWords.length-1));
    const extraSpaces = spacesNeeded % (lineWords.length-1);

    let line = "";
    for(let i =0;i<lineWords.length-1;i++) {
        line+=lineWords[i];
        line+=" ".repeat(spaceBetweenWords+ (i< extraSpaces ? 1 :0));
    }
    line += lineWords[lineWords.length-1];
    return line
}
const words = ["This","is","an","example","of","text","justification."];
const num = 16;
const result = fullJustify(words,num);
console.log(result);
console 命令行工具 X clear

                    
>
console