Search⌘ K

Solution to Justify Text

Explore how to justify text in JavaScript by applying a recursive function that uses the bestLineBreak method to split and format strings optimally. Understand the base and recursive cases for line breaking and see a practical example of functional programming in action to complete a text justification project.

We'll cover the following...

Final step. Justify text

In this step, use bestLineBreak function from the previous part to justify a given string.

Node.js
// helper function to recursively break lines
function justifyTextRecur(lineCostFunc, dict, width, text){
let [fst, snd] = bestLineBreak(lineCostFunc,dict, width, text);
if(snd.length === 0){
return [text]
}
return [fst, ...justifyTextRecur(lineCostFunc,dict,width,snd)];
}
function justifyText(lineCostFunc, dict, width, text){
return justifyTextRecur(lineCostFunc,dict,width, text.split(' '));
}
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
var text1 = "He who controls the past controls the future. He who controls the present controls the past."
var text2 = "A creative man is motivated by the desire to achieve, not by the desire to beat others."
console.log(justifyText(lineCost, enHyp, 12, text1));

Here, recursively call the bestLineBreak function to continuously break the line in the optimal way after splitting the string text into our representation ...