Last active
October 19, 2018 15:51
-
-
Save kziv/3722e568c2d6f0f5c35982e4651e601b to your computer and use it in GitHub Desktop.
joinWithConjunction
This file contains 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
joinWithConjunction(arr, delimiter, conjunction = 'and', useOxfordComma = true) { | |
switch (arr.length) { | |
case 0: | |
case 1: | |
// Use join behavior for these | |
return arr.join(delimiter); | |
case 2: | |
return arr.join(` ${conjunction} `); | |
default: | |
// We don't use a space between the two to make it work like String.join() | |
conjunction = useOxfordComma | |
? `${delimiter}${conjunction}` | |
: ` ${conjunction}`; | |
return `${arr.slice(0, -1).join(delimiter)}${conjunction} ${arr.slice(-1)}`; | |
} | |
} | |
/* ------------ MOCHA UNIT TESTS ------------- */ | |
describe('.joinWithConjunction', () => { | |
it('should return the only element if there is only one element', () => { | |
expect(joinWithConjunction(['A'], ', ')).to.equal('A'); | |
}); | |
it('should return the two elements joined with the conjunction and no delimiter if there are exactly two elements', () => { | |
expect(joinWithConjunction(['A', 'B'], ', ', 'or')).to.equal('A or B'); | |
}); | |
it('should return all elements joined with the conjunction and delimiter if there are more than two elements', () => { | |
expect(joinWithConjunction(['A', 'B', 'C'], ', ', 'or')).to.equal('A, B, or C'); | |
}); | |
it('should return all elements joined with the conjunction and delimiter with no last comma if the Oxford comma parameter is false', () => { | |
expect(joinWithConjunction(['A', 'B', 'C'], ', ', 'or', false)).to.equal('A, B or C'); | |
}); | |
it('should return all elements joined with the default conjunction if not passed in', () => { | |
expect(joinWithConjunction(['A', 'B', 'C'], ', ')).to.equal('A, B, and C'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment