Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tanvirstreame/5c913537a258fb643435f34781b71588 to your computer and use it in GitHub Desktop.
Save tanvirstreame/5c913537a258fb643435f34781b71588 to your computer and use it in GitHub Desktop.
Twitter (keeping list/map inside class)
class User {
constructor() {
this.users = new Map();
}
registerUser(userId, fullName, phone, age) {
if (!this.users.has(userId)) {
const newUser = { userId, fullName, phone, age };
this.users.set(userId, newUser);
return newUser;
}
return "User already exists";
}
}
class Follow {
constructor() {
this.follows = [];
}
addFollow(followee, follower) {
this.follows.push({ followee, follower });
}
getFollowees(userId) {
return this.follows
.filter(follow => follow.follower === userId)
.map(follow => follow.followee);
}
}
class Tweet {
constructor() {
this.tweets = [];
this.follows = new Follow(); // Initialize Follow inside Tweet
}
addTweet(userId, post) {
const newTweet = { userId, post };
this.tweets.push(newTweet);
return newTweet;
}
getFolloweeTweets(userId) {
const followeeList = this.follows.getFollowees(userId);
return this.tweets.filter(tweet => followeeList.includes(tweet.userId));
}
}
// Example usage:
// Initialize classes
const userSystem = new User();
const followSystem = new Follow();
const tweetSystem = new Tweet();
// Register users
userSystem.registerUser('u1', 'John Doe', '123-456-7890', 30);
userSystem.registerUser('u2', 'Jane Smith', '987-654-3210', 25);
// Add follow relationships
followSystem.addFollow('u2', 'u1'); // John follows Jane
// Add tweets
tweetSystem.addTweet('u1', 'Hello world!'); // John's tweet
tweetSystem.addTweet('u2', 'Good morning!'); // Jane's tweet
// Link follows to tweets
tweetSystem.follows = followSystem;
// Get followee tweets for user 'u1'
const followeeTweets = tweetSystem.getFolloweeTweets('u1');
console.log(followeeTweets);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment