Skip to content

Instantly share code, notes, and snippets.

@imliam
Last active November 21, 2017 14:07
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 imliam/cb1e6bb86bde755f1379b8ff23755a15 to your computer and use it in GitHub Desktop.
Save imliam/cb1e6bb86bde755f1379b8ff23755a15 to your computer and use it in GitHub Desktop.
/**
* Create an English sentence string from an array of items.
*
* @param {array} array [description]
* @param {string} separator Separator for list items. Defaults to ","
* @param {string} finalSeparator Separator for last item. Defaults to "and"
* @return {string} List as an English sentence.
*/
function listAsSentence(array, separator, finalSeparator)
{
separator = separator || ',';
finalSeparator = finalSeparator || 'and';
var str = '';
for (i = 0; i < array.length; i++) {
str = str + array[i];
if (typeof array[i + 1] !== 'undefined') {
if (typeof array[i + 2] === 'undefined') {
str += ' ' + finalSeparator + ' ';
} else {
str += separator + ' ';
}
}
}
return str;
}
listAsSentence(['a', 'b', 'c', 'd']); // a, b, c and d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment