Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
2.7. Format a list as "a, b and c"
Medium
Topics
This question is in
2. Strings and text"Liked by Ana, Ben and 12 others", "Ana and Ben are typing", "Shipping to India, Nepal or Bhutan": interfaces turn lists into phrases all the time. The phrase depends on the count (one name, two names, three or more) and on how much room there is, which is why such lists often name only the first few people and count the rest.
Write formatList(items, options) in format-list.js.
Signature
function formatList(items, { limit, conjunction = "and" } = {}) // a stringitems: an array of values to list.limit(optional): how many items to name before counting the rest.conjunction(optional): the word before the last part,"and"by default.
Requirements
- An empty list gives
""; one item gives that item; two give"a and b". - Three or more give the items separated by
", ", with" and "before the last:"a, b and c". There is no comma before"and". - With a
limit, when there are more items thanlimit, the firstlimititems are named and the rest are counted as the last part:"a, b and 2 others", or"1 other"when one is left. - A
limitequal to or larger than the number of items changes nothing. conjunctionreplaces"and", also before the count:"a, b or 2 others".- The options object and each option may be left out.
- Items are converted with
String; commas inside items are kept. - Throws a
RangeErrorfor alimitthat is not a positive integer (0, -1, 1.5,NaN,"2",Infinity), and aTypeErrorwhenitemsis not an array. - Does not change
items, and handles a list of 100,000 items with a limit quickly.
Examples
formatList([]); // ""
formatList(["Ana"]); // "Ana"
formatList(["Ana", "Ben"]); // "Ana and Ben"
formatList(["Ana", "Ben", "Cy"]); // "Ana, Ben and Cy"formatList(["Ana", "Ben", "Cy", "Dee"], { limit: 2 }); // "Ana, Ben and 2 others"
formatList(["Ana", "Ben", "Cy"], { limit: 2 }); // "Ana, Ben and 1 other"
formatList(["Ana", "Ben", "Cy"], { limit: 1 }); // "Ana and 2 others"formatList(["tea", "coffee", "juice"], { conjunction: "or" }); // "tea, coffee or juice"
formatList(["a", "b"], { limit: 0 }); // throws RangeErrorEnvironment
- Plain JavaScript in a browser page; the tests call the global
formatListfromformat-list.js. - English only; other languages and
Intl.ListFormatare not part of this problem. - Any built-in may be used.
Hints
- Once the limit is applied, is "2 others" any different from a name?
- How do you get every item but the last, and the last on its own?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…