Solution to Sub-task: Split Line
The solution to the Sub-task "Split line" of the project "Justify Text".
We'll cover the following...
Split line
In this step, take an array representation of the line and split it into two sub-array. The first sub-array satisfies the document width constraint.
Press + to interact
function splitLine(line, width){// Basecasesif (line.length === 0) return [[], []]; // length of line is zeroif (width === 0) return [[], line]; // document width is zerolet [head, ...rest] = line; // destructure line by removing first element// Recursive caseif(head.length <= width){// if width greater than first word length// Reccursively call for remaining line with decreased widthlet sub_answer = splitLine(rest, width - (head.length + 1))// Return by adding the first word into the recursive resultreturn [[head, ...sub_answer[0]],[...sub_answer[1]]];}else{// Also Basecasereturn [[], line];}}console.log(splitLine (["He", "who", "controls"], 15))console.log(splitLine (["A", "creative", "man"], 10))console.log(splitLine (["A", "creative", "man"], 11))console.log(splitLine (["A", "creative", "man"], 12))
The solution takes a recursive approach where the ...