...

/

Solution to Sub-task: best line break

Solution to Sub-task: best line break

The solution to the Sub-task "best line break" of the project "Justify Text".

We'll cover the following...

Best line break

In this final step, using functions from previous parts, we break a given line, maximize its length, and return the line with minimum cost using a cost function.

Press + to interact
// helper function to find length of the line
// input -> [String] eg. ['he', ' ', 'l', 'lo']
// Output -> [Number] eg. 6
/*
There is only one implicit space between two words. There is no implicit
space between a word and an explicit space character or two explicit space
characters. The function caters to that length.
*/
function lineLength(line){
if(line.length === 0) return 0;
if(line.length === 1) return line[0].length;
if(line[0] === ' '){
return 1 + lineLength(line.slice(1));
}
else{
return 1 + line[0].length + lineLength(line.slice(1));
}
}
function bestLineBreak(lineCostFunc, dict, width, line){
// split into possible lines
let possibleLines = lineBreaks(dict, width, line);
// add spaces
possibleLines = possibleLines
.map(x => {
// add blanks
let insertedBlanks = blankInsertions(width - lineLength(x[0]), x[0])
.map(y => [y, x[1]])
return insertedBlanks;
})
.reduce((prev, curr)=> prev.concat(curr), []); // flatten the array
// filter maximum length lines:
let maxLength = possibleLines.reduce((max, curr)=>{
return max > lineLength(curr[0]) ? max : lineLength(curr[0]);
},lineLength(possibleLines[0][0]))
// filter all lines of maxLength
possibleLines = possibleLines.filter(x => lineLength(x[0]) === maxLength);
let minimumCostLine = possibleLines.reduce((min, curr)=>{
return lineCostFunc(min[0]) > lineCostFunc(curr[0]) ? curr : min;
}, possibleLines[0]);
return minimumCostLine;
}
enHyp = {
"creative" : ["cr","ea","ti","ve"],
"controls" : ["co","nt","ro","ls"],
"achieve" : ["ach","ie","ve"],
"future" : ["fu","tu","re"],
"present" : ["pre","se","nt"],
"motivated" : ["mot","iv","at","ed"],
"desire" : ["de","si","re"],
"others" : ["ot","he","rs"],
}
const blankCost = 1.0
const blankProxCost = 1.0
const blankUnevenCost = 1.0
const hypCost = 1.0
console.log(bestLineBreak (lineCost, enHyp, 15, ["He", "who", "controls"]))

In this solution, take a line and do the following.

  1. Use lineBreaks function to split the line line and give all possible splits while incorporating broken-hyphenated words via dict ( ...