Greedy Wrap Fills Each Line To Width

Wrap text greedily so each line takes as many words as fit the width, keeping every returned line within the limit for terminal output.

JavascriptCli Tooling

Code

javascriptsnippet
23 lines
// Greedy wrapping: take as many words as fit the width, then break.
// Words never split mid-word and lines never end with a stray space.
function wrap(text, width) {
  const lines = [];
  let line = '';
  for (const word of text.split(/\s+/).filter(Boolean)) {
    if (!line) {
      line = word;
    } else if (line.length + 1 + word.length <= width) {
      line += ' ' + word;
    } else {
      lines.push(line);
      line = word;
    }
  }
  if (line) lines.push(line);
  return lines;
}

const wrapped = wrap('The quick brown fox jumps over a lazy dog near the river bank', 20);
for (const line of wrapped) {
  console.log(`|${line.padEnd(20)}|`);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

|The quick brown fox |
|jumps over a lazy   |
|dog near the river  |
|bank                |

How wrap fills each line

wrap(text, width) walks the words of text one at a time — text.split(/\s+/).filter(Boolean) skips runs of whitespace and drops the empties. The current candidate line lives in line: the first word on a line is taken unconditionally, and the branch line.length + 1 + word.length <= width decides whether appending the next word (plus one joining space) still fits the budget. When it does not fit, the finished line is pushed onto lines and the word starts the next line; the trailing if (line) lines.push(line) flushes the final segment after the loop ends.

What the demo prints

The demo wraps 'The quick brown fox jumps over a lazy dog near the river bank' at width 20 and prints each result padded by line.padEnd(20) between pipe characters. The run produces four lines:

|The quick brown fox |
|jumps over a lazy   |
|dog near the river  |
|bank                |

jumps did not fit next to fox, which is where the greedy split happens. The for...of loop inside wrap is the only loop over words — the later for loop in the demo section merely prints the finished lines and never touches wrap’s state, so the two loops are siblings, not nested.

The line that enforces the limit

} else if (line.length + 1 + word.length <= width) {
  line += ' ' + word;
}

Every accepted word keeps line.length at most width because the check counts the joining space. A single word longer than width still ends up alone on its own line via the else branch, so a produced line can only exceed the limit when one word alone does.

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `wrap` at load time.