Wrap Text to a Line Width

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write wrap(text, width), which breaks text into lines of at most width characters and returns them as an array of strings. Words are separated by one or more spaces (the text has no line breaks). Fill each line with as many words as fit, joined by single spaces, before starting the next, with no spaces at the start or end of a line. A word longer than width always starts a new line and is cut into pieces of width characters, each on its own line; its last piece then carries on like an ordinary word, so following words may join its line. Empty text, or text that is only spaces, gives an empty array. For example, wrap("The quick brown fox jumps over the lazy dog", 10) gives "The quick", "brown fox", "jumps over", "the lazy" and "dog".

Your code must pass

  • Fits as many words as possible on each line
  • Keeps short text on one line
  • Collapses extra spaces
  • Cuts words longer than the width
  • Returns no lines for empty text
  • Never goes over the width or loses text