Skip to content

Instantly share code, notes, and snippets.

@simonewebdesign
Created June 5, 2018 16:21
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 simonewebdesign/f74be021835550d78fe79b86ccd46c93 to your computer and use it in GitHub Desktop.
Save simonewebdesign/f74be021835550d78fe79b86ccd46c93 to your computer and use it in GitHub Desktop.
JavaScript Array.toSentence - inspired by Ruby's Array#to_sentence
// Transforms an array into a sentence.
// Example:
// toSentence(['apples', 'oranges', 'melons']);
// >> "apples, oranges and melons."
export function toSentence(arr) {
if (arr.length === 0) return '';
return arr.length > 1
? `${arr.slice(0, arr.length - 1).join(', ')} and ${arr.slice(-1)}.`
: `${arr[0]}.`;
}
describe('toSentence', () => {
it('joins an array into a comma-separated string, ending with a dot', () => {
expect(toSentence([])).to.eq('');
expect(toSentence(['dog'])).to.eq('dog.');
expect(toSentence(['foo', 'bar', 'baz'])).to.eq('foo, bar and baz.');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment