Skip to content

Instantly share code, notes, and snippets.

@tanvirstreame
Created December 2, 2023 09:21
Show Gist options
  • Save tanvirstreame/7bdbe55c6be474d549097040b44b521f to your computer and use it in GitHub Desktop.
Save tanvirstreame/7bdbe55c6be474d549097040b44b521f to your computer and use it in GitHub Desktop.
facebook
class User {
constructor(userId, userName) {
this.userId = userId;
this.userName = userName;
}
}
class Post {
constructor(userId, posts) {
this.userId = userId;
this.posts = posts;
}
}
class Friend {
constructor(follower, followee) {
this.follower = follower;
this.followee = followee;
}
}
class FacebookSystem {
constructor() {
this.users = new Map();
this.friends = [];
this.posts = [];
}
registerUser(userId, userName) {
if (!this.users.has(userId)) {
const newUser = new User(userId, userName);
this.users.set(userId, newUser);
return newUser;
}
return "User already existed";
}
addFriend(userId, friendId) {
this.friends.push(new Friend(userId, friendId))
this.friends.push(new Friend(friendId, userId))
return "Added as friend"
}
removeFriend(userId, friendId) {
this.friends = this.friends.filter(friend => !(friend.followee === userId && friend.follower === friendId));
this.friends = this.friends.filter(friend => !(friend.followee === friendId && friend.follower === userId));
return "Unfiended successfully";
}
addPost(userId, posts) {
this.posts.push(new Post(userId, posts));
return "Added post successfully";
}
getFriendPosts(userId) {
const friendList = this.friends.filter(eachUser => eachUser.follower === userId).map(friend => friend.followee)
return this.posts.filter(post => friendList.includes(post.userId))
}
}
const facebookSystem = new FacebookSystem();
facebookSystem.registerUser(1, 'Tanvir');
facebookSystem.registerUser(2, 'Nadim');
facebookSystem.addFriend(1, 2);
facebookSystem.addPost(1, 'Hello, friends!');
facebookSystem.addPost(2, 'Hi, a!');
console.log("friendPost", facebookSystem.getFriendPosts(1));
facebookSystem.removeFriend(1, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment