Skip to content

Instantly share code, notes, and snippets.

@etjossem
Last active July 3, 2017 20:26
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 etjossem/9e9d1c06d8006931f0b81936d113f1e2 to your computer and use it in GitHub Desktop.
Save etjossem/9e9d1c06d8006931f0b81936d113f1e2 to your computer and use it in GitHub Desktop.
OxfordComma.js -- don't leave home without it.
// Defaults to giving a fuck about an Oxford Comma
var OxfordComma = function(array, gaf) {
var gaf = (typeof gaf === 'undefined') ? true : gaf;
var output = "";
if (array.length <= 1) {
output = array.toString();
} else if (array.length == 2) {
output = array.join(" and ");
} else {
var lastItem = array.pop();
array = array.join(", ");
if (gaf) {
output = array + ", and " + lastItem;
} else {
output = array + " and " + lastItem;
}
}
return output;
}
// Usage
var edwards = ["Ed","Edd","Eddy"];
console.log(OxfordComma(edwards));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment