Skip to content

Instantly share code, notes, and snippets.

@chriskirknielsen
Created June 6, 2023 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriskirknielsen/d1eb51ffd421bae7746d54edb2cf2d02 to your computer and use it in GitHub Desktop.
Save chriskirknielsen/d1eb51ffd421bae7746d54edb2cf2d02 to your computer and use it in GitHub Desktop.
Oxford Comma list
/**
* Take a list of items and combine them into a string, with an Oxford comma for the last item.
* @param {string[]} list Items to list into a string.
* @returns {string} Comma-separated list of items.
*/
function toOxfordCommaList(list) {
let strList = '';
if (list.length > 2) {
list[list.length - 1] = `and ${list[list.length - 1]}`; // Inject "and" before the last item
strList = list.join(', ');
} else {
strList = list.join(' and '); // A single value won't get a separator so we can use this for both one and two item values
}
return strList;
}
// Example:
const elements = ['Wind', 'Earth', 'Water', 'Fire'];
toOxfordCommaList(elements); // "Wind, Earth, Water, and Fire"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment