Skip to content

Commit bf79b63

Browse files
committed
4.7. mostLikes function
Pretty much copy paste from mostBlogs
1 parent e86981d commit bf79b63

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

part4/tests/mostLikes.test.js

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const listHelper = require('../utils/list_helper')
2+
const arrays = require('./arrays')
3+
4+
describe('most likes', () => {
5+
test('of empty list is empty object', () => {
6+
const result = listHelper.mostLikes([])
7+
expect(result).toEqual({})
8+
})
9+
10+
test('when list has only one blog that author and amount of likes matches', () => {
11+
const result = listHelper.mostLikes(arrays.listWithOneBlog)
12+
const expected = {
13+
author: arrays.listWithOneBlog[0].author,
14+
likes: arrays.listWithOneBlog[0].likes,
15+
}
16+
expect(result).toEqual(expected)
17+
})
18+
19+
test('with multiple blogs is calculated right', () => {
20+
const result = listHelper.mostLikes(arrays.blogs)
21+
const expected = {
22+
author: 'Edsger W. Dijkstra',
23+
likes: 17,
24+
}
25+
expect(result).toEqual(expected)
26+
})
27+
})

part4/utils/list_helper.js

+17
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,26 @@ const mostBlogs = (blogs) => {
2727
return { author: max, blogs: authors[max] }
2828
}
2929

30+
const mostLikes = (blogs) => {
31+
if (blogs.length === 0) return {}
32+
33+
const reducer = (max, item) => {
34+
max[item.author]
35+
? (max[item.author] += item.likes)
36+
: (max[item.author] = item.likes)
37+
return max
38+
}
39+
const authors = blogs.reduce(reducer, {})
40+
const max = Object.keys(authors).reduce((a, b) =>
41+
authors[a] > authors[b] ? a : b
42+
)
43+
return { author: max, likes: authors[max] }
44+
}
45+
3046
module.exports = {
3147
dummy,
3248
totalLikes,
3349
favoriteBlog,
3450
mostBlogs,
51+
mostLikes,
3552
}

0 commit comments

Comments
 (0)