Skip to content

Instantly share code, notes, and snippets.

@hughevans
Created February 3, 2014 02:45
Show Gist options
  • Save hughevans/8778157 to your computer and use it in GitHub Desktop.
Save hughevans/8778157 to your computer and use it in GitHub Desktop.
Javascript Array toSentence()
Array.prototype.toSentence = (oxfordComma) ->
firstWord = if typeof this[0] is 'string' then this[0].charAt(0).toUpperCase() + this[0].slice(1) else this[0]
conjunction = if oxfordComma then ', and' else ' and'
switch @length
when 0 then ''
when 1 then "#{firstWord}."
when 2 then "#{firstWord} and #{this[1]}."
else "#{firstWord}, #{@slice(1, -1).join(', ')}#{conjunction} #{this[@length - 1]}."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment