Created
June 5, 2018 16:21
-
-
Save simonewebdesign/f74be021835550d78fe79b86ccd46c93 to your computer and use it in GitHub Desktop.
JavaScript Array.toSentence - inspired by Ruby's Array#to_sentence
This file contains hidden or 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
// 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]}.`; | |
} |
This file contains hidden or 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
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