Shorten Text at a Word Boundary

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

The problem

  • easy
  • Code

Write truncate(text, max), where max is at least 2 and words in text are separated by spaces. If text has max characters or fewer, return it unchanged. Otherwise keep as many whole words from the start as fit in max minus 1 characters, drop any spaces left at the end, and add the ellipsis character "…" (one character, not three dots), so the result is never longer than max. If not even the first word fits, cut it to max minus 1 characters and add the ellipsis. For example, truncate("The quick brown fox", 12) is "The quick…".

Your code must pass

  • Returns text that fits unchanged
  • Cuts at the last whole word and adds an ellipsis
  • Drops spaces before the ellipsis
  • Cuts a first word that doesn't fit
  • Never goes over max