Advertisement
Guest User

mini-twitter.js

a guest
Dec 15th, 2019
1,562
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class FakeTwitter {
  2.   constructor(props) {
  3.     this.redisDatabase = {};
  4.   }
  5.  
  6.   addFollower(user_id, follower_id) {
  7.     // When someone follows the user, store his/her data
  8.     this.redisDatabase[user_id].followers.push(follower_id);
  9.   }
  10.  
  11.   createUser(id) {
  12.     // When you create the user,
  13.     // create an empty container in redis to hold their timeline
  14.     this.redisDatabase[id] = { followers: [], timeline: [], tweets: [] };
  15.   }
  16.  
  17.   recordTweet(id, tweetText) {
  18.     // when someone tweets, record the tweet
  19.     this.redisDatabase[id].tweets.push(tweetText);
  20.  
  21.     // then find all his followers
  22.     // and push the tweet into their timeline array.
  23.     // like the way post offices send mails to your box.
  24.     let followers = this.redisDatabase[id].followers;
  25.  
  26.     for (const follower of followers) {
  27.       // Ideally you should be pushing id's not text
  28.       // but this is just a demo for you to understand what's going on
  29.       this.redisDatabase[follower].timeline.push({
  30.         id,
  31.         tweet: tweetText
  32.       });
  33.     }
  34.   }
  35.  
  36.   retweet(retweeted_by, tweetText) {
  37.     // when you retweet, we record the tweet
  38.     this.recordTweet(retweeted_by, tweetText);
  39.   }
  40.  
  41.   refreshTimeline(id) {
  42.     // When someone refreshes their timeline
  43.     // Just pull the timeline from the database
  44.     return this.redisDatabase[id].timeline;
  45.   }
  46.  
  47.   preview(id) {
  48.     // preview of our datastore
  49.     console.log(this.redisDatabase[id]);
  50.   }
  51. }
  52.  
  53. // Sample Usage
  54.  
  55. // setup instance
  56. const Twitter = new FakeTwitter();
  57. // create an account for me
  58. Twitter.createUser("griffith");
  59. // create an account for you
  60. Twitter.createUser("eustace");
  61. // add a new follower
  62. Twitter.addFollower("griffith", "eustace");
  63. // Record my tweet
  64. Twitter.recordTweet("griffith", "Eustace is a hoe?");
  65.  
  66. // Inspect the whole object to see what's going on
  67. console.log(Twitter);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement