diff --git a/parts/4/blogApp/src/utils.js b/parts/4/blogApp/src/utils.js index e2f9ea5..eadc74d 100644 --- a/parts/4/blogApp/src/utils.js +++ b/parts/4/blogApp/src/utils.js @@ -42,10 +42,30 @@ const favoritePost = (posts) => { return favoritePost; }; +const mostPosts = (posts) => { + if (!posts || posts.length === 0) { + return null; + } + + const countMap = posts.reduce((acc, post) => { + acc[post.author] = (acc[post.author] || 0) + 1; + return acc; + }, {}); + + // Use Object.entries to find the top author + const [author, postsCount] = Object.entries(countMap).reduce( + (max, entry) => (entry[1] > max[1] ? entry : max), + ['', 0] + ); + + return { author, posts: postsCount }; +}; + module.exports = { reverse, average, listHelper, totalLikes, favoritePost, + mostPosts, }; diff --git a/parts/4/blogApp/tests/mostPosts.test.js b/parts/4/blogApp/tests/mostPosts.test.js new file mode 100644 index 0000000..1b32452 --- /dev/null +++ b/parts/4/blogApp/tests/mostPosts.test.js @@ -0,0 +1,54 @@ +const { test, describe } = require("node:test"); +const assert = require("node:assert"); +const { mostPosts } = require("../src/utils"); + +describe("most posts ", () => { + const posts = [ + { + _id: "5a422aa71b54a676234d17f8", + title: "Go To Statement Considered Harmful", + author: "Edsger W. Dijkstra", + url: "https://homepages.cwi.nl/~storm/teaching/reader/Dijkstra68.pdf", + likes: 5, + __v: 0, + }, + { + _id: "5a422aa71b54a676234d17f8", + title: "Go To Statement Considered Harmful", + author: "Edsger W. Dijkstra", + url: "https://homepages.cwi.nl/~storm/teaching/reader/Dijkstra68.pdf", + likes: 2, + __v: 0, + }, + { + _id: "123", + title: "Lololo", + author: "John Doe", + url: "https://homepages.cwi.nl/~storm/teaching/reader/Dijkstra68.pdf", + likes: 1, + __v: 0, + }, + ]; + + const emptyArray = []; + + const gibberish = "asdaSd123asd"; + + test("finds top author properly", () => { + assert.deepStrictEqual(mostPosts(posts), { + author: "Edsger W. Dijkstra", + posts: 2, + }); + }); + + test("works fine with empty array", () => { + assert.strictEqual(mostPosts(emptyArray), null); + }); + + test("fails with gibberish input", () => { + const failedCall = () => { + mostPosts(gibberish); + }; + assert.throws(failedCall, Error); + }); +}); diff --git a/parts/4/notes.md b/parts/4/notes.md index 8263903..ccd63b9 100644 --- a/parts/4/notes.md +++ b/parts/4/notes.md @@ -4,3 +4,4 @@ Exercises: * [X] 4.3 * [X] 4.4 * [X] 4.5 +* [X] 4.6