Last active
May 19, 2024 06:30
-
-
Save tanvirstreame/948b2c676b1704acee4e07e707a40bdb to your computer and use it in GitHub Desktop.
Facebook system (Keeping list/map inside each class)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User { | |
constructor() { | |
if (!User.users) { | |
User.users = new Map(); | |
} | |
} | |
static registerUser(userId, userName) { | |
if (!User.users.has(userId)) { | |
const newUser = { userId, userName }; | |
User.users.set(userId, newUser); | |
return newUser; | |
} | |
return "User already existed"; | |
} | |
} | |
class Post { | |
constructor() { | |
if (!Post.posts) { | |
Post.posts = []; | |
} | |
} | |
static addPost(userId, postContent) { | |
Post.posts.push({ userId, posts: postContent }); | |
return "Added post successfully"; | |
} | |
static getPosts() { | |
return Post.posts; | |
} | |
} | |
class Friend { | |
constructor() { | |
if (!Friend.friends) { | |
Friend.friends = []; | |
} | |
} | |
static addFriend(userId, friendId) { | |
Friend.friends.push({ follower: userId, followee: friendId }); | |
Friend.friends.push({ follower: friendId, followee: userId }); | |
return "Added as friend"; | |
} | |
static removeFriend(userId, friendId) { | |
Friend.friends = Friend.friends.filter(friend => !(friend.followee === userId && friend.follower === friendId)); | |
Friend.friends = Friend.friends.filter(friend => !(friend.followee === friendId && friend.follower === userId)); | |
return "Unfriended successfully"; | |
} | |
static getFriends() { | |
return Friend.friends; | |
} | |
static getFriendPosts(userId) { | |
const friendList = Friend.friends.filter(friend => friend.follower === userId).map(friend => friend.followee); | |
return Post.getPosts().filter(post => friendList.includes(post.userId)); | |
} | |
static searchFriendPosts(userId, search) { | |
const friendList = Friend.friends.filter(friend => friend.follower === userId).map(friend => friend.followee); | |
const postList = Post.getPosts().filter(post => friendList.includes(post.userId)); | |
return postList.filter(post => post.posts.toLowerCase().includes(search.toLowerCase())); | |
} | |
} | |
// Usage example: | |
User.registerUser(1, 'Tanvir'); | |
User.registerUser(2, 'Nadim'); | |
Friend.addFriend(1, 2); | |
Post.addPost(1, 'Hello, friends!'); | |
Post.addPost(2, 'Hi, Bangladesh!'); | |
console.log("friendPost", Friend.getFriendPosts(1)); | |
console.log("friendPost search", Friend.searchFriendPosts(1, "bangladesh")); | |
Friend.removeFriend(1, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment