-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy path(6 kyu) Help the bookseller.js
48 lines (46 loc) · 1.27 KB
/
(6 kyu) Help the bookseller.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
// #1 Use forEach
// function stockList(listOfArt, listOfCat) {
// if (!listOfArt.length || !listOfCat.length) {
// return '';
// }
// const books = {};
// const result = [];
// listOfArt.forEach((book) => {
// const [title, num] = book.split` `;
// books[title[0]] = books[title[0]] ? (books[title[0]] += +num) : +num;
// });
// listOfCat.forEach((letter) => {
// const num = books[letter] || 0;
// result.push(`(${letter} : ${num})`);
// });
// return result.join` - `;
// }
// #2 Optimazed forEach
// function stockList(listOfArt, listOfCat) {
// if (!listOfArt.length || !listOfCat.length) {
// return '';
// }
// const books = {};
// listOfArt.forEach((book) => {
// const title = book[0];
// books[title] = (books[title] | 0) + +book.split` `[1];
// });
// return listOfCat.map((letter) => {
// return `(${letter} : ${books[letter] | 0})`;
// }).join` - `;
// }
// #3 Use reduce
function stockList(listOfArt, listOfCat) {
if (!listOfArt.length || !listOfCat.length) {
return '';
}
return listOfCat
.map((book) => {
const sum = listOfArt.reduce(
(acc, title) => acc + (title[0] === book ? +title.split(' ')[1] : 0),
0,
);
return `(${book} : ${sum})`;
})
.join(' - ');
}