CodePark/ problems / Format a list in English
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Parsing and building strings

Format a list in English

mediumabout 20 minutes in an interview

Implement listFormat(items, options). It turns an array of strings into a readable English list, the kind you see in "Ada, Linus and 2 others liked this".

Basic format:

  • no items: ""
  • one item: the item itself, "Ada"
  • two items: "Ada and Linus"
  • three or more: commas between items and and before the last, with no comma before and: "Ada, Linus and Grace"

Options are all optional. First drop empty strings, then apply the options in this order:

  1. unique: true removes repeats, keeping each item's first occurrence.
  2. sorted: true sorts the items in ascending order with the default sort(), which compares UTF-16 code units.
  3. length: n shows only the first n items, then and K others, where K is how many were left out. Use other when K is 1. If n is not a positive number smaller than the item count, ignore it.

Don't modify items, and don't use Intl.ListFormat.

Input: listFormat(['Ada', 'Linus', 'Grace']) Output: 'Ada, Linus and Grace'
Input: listFormat(['Ada', 'Linus', 'Grace', 'Alan'], { length: 2 }) Output: 'Ada, Linus and 2 others'
Input: listFormat(['b', 'a', 'b', 'c'], { unique: true, sorted: true, length: 2 }) Output: 'a, b and 1 other'