master
1/***
2 * @method toSentence([conjunction] = 'and')
3 * @author nadinengland
4 * @returns String
5 * @dependencies Array
6 * @short Builds a grammatical list from the array.
7 * @extra A custom string [conjuction] can be supplied for localization, 'and' is used if not a string.
8 * @example
9 *
10 * ['a', 'b', 'c'].toSentence() -> 'a, b and c';
11 * ['a', 2, {c:3}].toSentence() -> 'a, 2 and [object Object]';
12 * ['Lundi', 'Mardi', 'Mercredi'].toSentence('et') -> 'Lundi, Mardi et Mercredi';
13 *
14 ***/
15
16Array.extend({
17
18 'toSentence': function(conjunction) {
19 var sentence = "",
20 twoWordConjunction,
21 lastWordConjunction;
22
23 // Quick escape
24 if (this.length === 0) return sentence;
25
26 if (typeof conjunction !== 'string') {
27 conjunction = "and";
28 }
29
30 twoWordConjunction = ' ' + conjunction + ' ';
31 lastWordConjunction = ' ' + conjunction + ' ';
32
33 switch (this.length) {
34 case 1:
35 sentence = this[0];
36 break;
37 case 2:
38 sentence = this.join(twoWordConjunction);
39 break;
40 default:
41 sentence = this.first(this.length - 1).join(', ') + lastWordConjunction + this.last();
42 break;
43 };
44
45 return sentence;
46 }
47
48});