Overview
Implement listFormat(items, options) — formats an array into a grammatically correct string.
{ type: 'conjunction' }→ uses "and" (default){ type: 'disjunction' }→ uses "or"
Examples
listFormat(['a','b','c']); // 'a, b, and c'
listFormat(['a','b'], { type: 'disjunction' }); // 'a or b'Solution
Reveal solution
function listFormat(items, options) {
const word = (options?.type === 'disjunction') ? 'or' : 'and';
if (items.length === 0) return '';
if (items.length === 1) return items[0];
if (items.length === 2) return `${items[0]} ${word} ${items[1]}`;
return items.slice(0, -1).join(', ') + `, ${word} ` + items[items.length - 1];
}list-format.js
List Format
mediumcodingJavaScriptStrings
Overview
Implement listFormat(items, options) — formats an array into a grammatically correct string.
{ type: 'conjunction' }→ uses "and" (default){ type: 'disjunction' }→ uses "or"
Examples
listFormat(['a','b','c']); // 'a, b, and c'
listFormat(['a','b'], { type: 'disjunction' }); // 'a or b'Solution
Reveal solution
function listFormat(items, options) {
const word = (options?.type === 'disjunction') ? 'or' : 'and';
if (items.length === 0) return '';
if (items.length === 1) return items[0];
if (items.length === 2) return `${items[0]} ${word} ${items[1]}`;
return items.slice(0, -1).join(', ') + `, ${word} ` + items[items.length - 1];
}NameTopicDifficulty
103 of 103 problems