-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
format-a-string-of-names-like-bart-lisa-and-maggie.js
110 lines (96 loc) · 2.38 KB
/
format-a-string-of-names-like-bart-lisa-and-maggie.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
function list(names) {
// a place to store the sentence
let sentence = '';
// iterate over the names
for (let i = 0; i < names.length; i++) {
const { name } = names[i];
// if the current index is the last index,
if (i == names.length - 1) {
// append the name to the sentence with nothing after
sentence += name;
} else if (i == names.length - 2) {
// if the current index is the second to last index,
// append the name to the sentence with an & after
sentence += name + ' & ';
} else {
// otherwise append the name with a comma after
sentence += name + ', ';
}
}
// return the sentence
return sentence;
}
function list(names) {
return names.reduce((sentence, { name }, i) => {
if (i == names.length - 1) {
return sentence + name;
} else if (i == names.length - 2) {
return sentence + name + ' & ';
} else {
return sentence + name + ', ';
}
}, '');
}
function list(names) {
return names.map(({ name }, i) => {
if (i == names.length - 1) {
return name;
} else if (i == names.length - 2) {
return name + ' & ';
} else {
return name + ', ';
}
}).join('');
}
function list(names) {
let allnames = names
.map(person => person.name)
.join(', ');
if (names.length > 1) {
const lastCommaIndex = allnames.lastIndexOf(',');
allnames = allnames.substring(0, lastCommaIndex) + ' &' + allnames.substring(lastCommaIndex + 1);
}
return allnames;
}
function list(names) {
let allnames = names
.map(person => person.name)
.join(', ');
if (names.length > 1) {
const lastCommaIndex = allnames.lastIndexOf(',');
const replacedNames = allnames.split('');
replacedNames.splice(lastCommaIndex, 1, ' &');
allnames = replacedNames.join('');
}
return allnames;
}
console.log(list([{
name: 'Bart'
}, {
name: 'Lisa'
}, {
name: 'Maggie'
}, {
name: 'Homer'
}, {
name: 'Marge'
}]), 'Bart, Lisa, Maggie, Homer & Marge',
'Must work with many names');
console.log(list([{
name: 'Bart'
}, {
name: 'Lisa'
}, {
name: 'Maggie'
}]), 'Bart, Lisa & Maggie',
'Must work with many names');
console.log(list([{
name: 'Bart'
}, {
name: 'Lisa'
}]), 'Bart & Lisa',
'Must work with two names');
console.log(list([{
name: 'Bart'
}]), 'Bart', 'Wrong output for a single name');
console.log(list([]), '', 'Must work with no names');