-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormatAStringOfNames.js
More file actions
44 lines (31 loc) · 971 Bytes
/
Copy pathFormatAStringOfNames.js
File metadata and controls
44 lines (31 loc) · 971 Bytes
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
// URL: https://www.codewars.com/kata/format-a-string-of-names-like-bart-lisa-and-maggie/train/javascript
// Description:
/*
Given: an array containing hashes of names
Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.
Example:
list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ])
// returns 'Bart, Lisa & Maggie'
list([ {name: 'Bart'}, {name: 'Lisa'} ])
// returns 'Bart & Lisa'
list([ {name: 'Bart'} ])
// returns 'Bart'
list([])
// returns ''
Note: all the hashes are pre-validated and will only contain A-Z, a-z, '-' and '.'.
*/
// Code
function list(names) {
let sentence = '';
for (let i = 0; i < names.length; i++) {
const { name } = names[i];
if (i == names.length - 1) {
sentence += name;
} else if (i == names.length - 2) {
sentence += name + ' & ';
} else {
sentence += name + ', ';
}
}
return sentence;
}