List FormatLoading saved progress…

List Format

Implement listFormat(items, conjunction = 'and') that joins an array of strings into a grammatical English list. A bare items.join(', ') gives you 'a, b, c' — fine for a CSV, wrong for a sentence. People write lists differently: the final item gets a conjunction (and, or) in front of it, and a two-item list drops the comma entirely. Your job is to reproduce those rules.

Signature

// items:        string[]   — the list items, in order.
// conjunction:  string     — the word before the final item; defaults to 'and'.
// returns:      string     — the items joined into one grammatical list.
function listFormat(items, conjunction = 'and'): string;

Examples

listFormat([]);                          // → ''
listFormat(['apple']);                   // → 'apple'
listFormat(['apple', 'banana']);         // → 'apple and banana'
listFormat(['a', 'b', 'c']);             // → 'a, b and c'
// A custom conjunction replaces the default.
listFormat(['a', 'b', 'c'], 'or');       // → 'a, b or c'
listFormat(['tea', 'coffee'], 'or');     // → 'tea or coffee'

Notes

  • Zero and one are special. An empty array returns ''; a single item returns that item with nothing added.
  • Two items get no comma. ['a', 'b'] becomes 'a and b', not 'a, and b'. The comma only appears once there are three or more items.
  • No Oxford comma. Three items produce 'a, b and c' — there is no comma before the conjunction. (The Oxford-comma variant would write 'a, b, and c'; this base version does not.)
  • The conjunction sits before the last item only. It never appears between the earlier items, which are joined by ', '.
  • The conjunction is configurable. It defaults to 'and' but the caller can pass 'or' (or anything else).
  • Don't mutate the input. Read items; build a fresh string. Items containing spaces ('New York') must be preserved as-is.
Loading editor…