exercise 4.6 completed

This commit is contained in:
Pablo Martin 2025-06-05 15:44:55 +02:00
parent 0309a2cc95
commit e51f318929
3 changed files with 75 additions and 0 deletions

View file

@ -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,
};

View file

@ -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);
});
});

View file

@ -4,3 +4,4 @@ Exercises:
* [X] 4.3
* [X] 4.4
* [X] 4.5
* [X] 4.6