Drill

ProblemsTypeScript › text

Wrap text to a label width

hardtextTypeScript

A shipping label printer takes a fixed number of characters per line, and a description has to be broken across lines without splitting words.

wordWrap(text: string, width: int) → list<string>

Solve it in the editor →

Where you start

function wordWrap(text: string, width: number): string[] {
  
}

Worked examples

CallResult
wordWrap("the quick brown fox", 10)["the quick","brown fox"]
wordWrap("a bb ccc", 3)["a","bb","ccc"]
wordWrap("supercalifragilistic is long", 5)["supercalifragilistic","is","long"]
wordWrap("one two", 20)["one two"]

Hint

Track the current line as a string. Before adding a word, check whether the line plus a space plus the word still fits.

Reference solution in TypeScript
function wordWrap(text: string, width: number): string[] {
  if (width <= 0) return [];
  const words = text.split(/\s+/).filter((w) => w.length > 0);
  const lines: string[] = [];
  let line = '';
  for (const w of words) {
    if (line === '') line = w;
    else if (line.length + 1 + w.length <= width) line += ' ' + w;
    else {
      lines.push(line);
      line = w;
    }
  }
  if (line !== '') lines.push(line);
  return lines;
}

The same problem in another language

More text problems in TypeScript