Skip to content

Instantly share code, notes, and snippets.

@seawolf
Last active January 31, 2018 15:46
Show Gist options
  • Save seawolf/ecf025a7ec9a0a630b577e34231eb69c to your computer and use it in GitHub Desktop.
Save seawolf/ecf025a7ec9a0a630b577e34231eb69c to your computer and use it in GitHub Desktop.
List Join
function joinListOfStrings(list = [], separator = ',', conjunction = 'and', oxfordComma = false) {
switch (list.length) {
case 0:
return '';
case 1:
return list[0];
case 2:
return list.join( (oxfordComma ? ', ' : ' ') + conjunction + ' ');
default:
var lastTwoParts = list.splice(-2);
var easyBit = list.join(separator + ' ') + separator + ' ';
return easyBit + lastTwoParts.join( (oxfordComma ? ', ' : ' ') + conjunction + ' ');
}
};
@seawolf
Copy link
Author

seawolf commented Jan 31, 2018

joinListOfStrings();
joinListOfStrings(['Alpha']);
joinListOfStrings(['Alpha', 'Beta']);
joinListOfStrings(['Alpha', 'Beta'], ',', 'or');
joinListOfStrings(['Alpha', 'Beta'], ',', 'or', true);
joinListOfStrings(['Alpha', 'Beta', 'Zeta']);
joinListOfStrings(['Alpha', 'Beta', 'Zeta'], ',', 'or');
joinListOfStrings(['Alpha', 'Beta', 'Zeta'], ',', 'or', true);
joinListOfStrings(['Alpha', 'Beta', 'Zeta'], ' +', 'or', true);
""
"Alpha"
"Alpha and Beta"
"Alpha or Beta"
"Alpha, or Beta"
"Alpha, Beta and Zeta"
"Alpha, Beta or Zeta"
"Alpha, Beta, or Zeta"
"Alpha + Beta, or Zeta"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment