Created
June 6, 2023 21:42
-
-
Save chriskirknielsen/d1eb51ffd421bae7746d54edb2cf2d02 to your computer and use it in GitHub Desktop.
Oxford Comma list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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