-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path355.Design_Twitter.js
111 lines (104 loc) · 2.81 KB
/
355.Design_Twitter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
type userId = number;
interface tweetIdInfo {
tweetId: number;
order: number;
}
interface User {
tweetIds: tweetIdInfo[];
follows: userId[];
followers: userId[];
}
class Twitter {
private userMap: Map<userId, User>;
private order: number;
constructor() {
this.userMap = new Map<userId, User>();
this.order = 0; // 自定order保证顺序
}
postTweet(userId: number, tweetId: number): void {
const {
tweetIds = [],
follows = [],
followers = [],
} = this.userMap.get(userId) || {};
this.userMap.set(userId, {
tweetIds: [...tweetIds, { tweetId, order: ++this.order }],
follows,
followers,
});
}
getNewsFeed(userId: number): number[] {
const { tweetIds = [], follows = [] } = this.userMap.get(userId) || {};
let allTweetIds = [...tweetIds];
for (const follow of follows) {
const followTweetIds = this.userMap.get(follow)?.tweetIds || [];
allTweetIds = [...allTweetIds, ...followTweetIds];
}
allTweetIds.sort((x, y) => y.order - x.order);
return allTweetIds.slice(0, 10).map((item) => item.tweetId);
}
follow(followerId: number, followeeId: number): void {
// 新增关注者
const {
tweetIds = [],
follows = [],
followers = [],
} = this.userMap.get(followerId) || {};
this.userMap.set(followerId, {
tweetIds,
follows: Array.from(new Set([...follows, followeeId])), // 重复关注需要去重
followers,
});
// 新增粉丝
const {
tweetIds: tweetIdsC,
follows: followsC,
followers: followersC,
} = this.userMap.get(followeeId) || {
tweetIds: [],
follows: [],
followers: [],
};
this.userMap.set(followeeId, {
tweetIds: tweetIdsC,
follows: followsC,
followers: Array.from(new Set([...followersC, followerId])), // 重复关注需要去重
});
}
unfollow(followerId: number, followeeId: number): void {
// 减少关注者
const {
tweetIds = [],
follows = [],
followers = [],
} = this.userMap.get(followerId) || {};
this.userMap.set(followerId, {
tweetIds,
follows: follows.filter((id) => id !== followeeId),
followers,
});
// 减少粉丝
const {
tweetIds: tweetIdsC,
follows: followsC,
followers: followersC,
} = this.userMap.get(followeeId) || {
tweetIds: [],
follows: [],
followers: [],
};
this.userMap.set(followeeId, {
tweetIds: tweetIdsC,
follows: followsC,
followers: followersC.filter((id) => id !== followerId),
});
}
}
/**
* Your Twitter object will be instantiated and called as such:
* var obj = new Twitter()
* obj.postTweet(userId,tweetId)
* var param_2 = obj.getNewsFeed(userId)
* obj.follow(followerId,followeeId)
* obj.unfollow(followerId,followeeId)
*/