fullstackopen-notes/parts/4/blogApp/src/utils.js
2025-06-05 15:48:19 +02:00

89 lines
1.7 KiB
JavaScript

const reverse = (string) => {
return string.split("").reverse().join("");
};
const average = (array) => {
const reducer = (sum, item) => {
return sum + item;
};
return array.length === 0 ? 0 : array.reduce(reducer, 0) / array.length;
};
const listHelper = (posts) => {
console.log("lol");
return 1;
};
const totalLikes = (posts) => {
if (!posts) {
return 0;
}
const likeCount = posts
.map((post) => post.likes)
.reduce((cum, value) => cum + value, 0);
return likeCount;
};
const favoritePost = (posts) => {
if (!posts || posts.length === 0) {
return null;
}
const highestLikes = posts.reduce(
(max, post) => (post.likes > max ? (max = post.likes) : max),
0
);
const favoritePost = posts.find((post) => post.likes == highestLikes);
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;
}, {});
const [author, postsCount] = Object.entries(countMap).reduce(
(max, entry) => (entry[1] > max[1] ? entry : max),
['', 0]
);
return { author, posts: postsCount };
};
const mostLikes = (posts) => {
if (!posts || posts.length === 0) {
return null;
}
const likesMap = posts.reduce((acc, post) => {
acc[post.author] = (acc[post.author] || 0) + post.likes;
return acc;
}, {});
const [author, likesCount] = Object.entries(likesMap).reduce(
(max, entry) => (entry[1] > max[1] ? entry : max),
['', 0]
);
return { author, likes: likesCount };
};
module.exports = {
reverse,
average,
listHelper,
totalLikes,
favoritePost,
mostPosts,
mostLikes
};