Last active
November 21, 2017 14:07
-
-
Save imliam/cb1e6bb86bde755f1379b8ff23755a15 to your computer and use it in GitHub Desktop.
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
/** | |
* 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