😎풀이

  1. 트윗을 담당할 posts 선언
  2. 팔로우 상태를 연결할 followStatus 선언
  3. postTweet할 경우 게시물 배열에 추가하고 내가 조회할 수 있게 내 팔로잉 목록에 자신 추가
  4. getNewsFeed할 경우 게시물을 역순으로 조회하며 내가 팔로우 하는 회원의 글 인 경우 뉴스피드에 추가
  5. follow할 경우 내 follow 목록에 추가
  6. unfollow할 경우 내 follow 목록에서 제거
class Twitter {
    // 트윗 [[유저 아이디, 트윗 아이디]]
    private posts: number[][]
    // 팔로우 상태 (key: 내 아이디, value: Set(팔로잉 회원 아이디))
    private followStatus: Map<number, Set<number>>
    constructor() {
        this.posts = []
        this.followStatus = new Map<number, Set<number>>()
    }
    postTweet(userId: number, tweetId: number): void {
        // 게시물에 배열 형태로 포스트 정보 입력 
        this.posts.push([userId, tweetId])
        // 업로드 회원은 본인 게시물 조회가 가능해야 하므로 자신 팔로우
        if(!this.followStatus.has(userId)) this.followStatus.set(userId, new Set([userId]))
    }
    getNewsFeed(userId: number): number[] {
        // 팔로워 조회
        const myFollowers = this.followStatus.get(userId)
        if(!myFollowers) return []
        const newsFeeds = []
        // 최신순 정렬 되어야 하므로 역순으로 조회하며 팔로우 중이라면 newsFeeds에 추가
        for(let i = this.posts.length - 1; i >= 0; i--) {
            if(newsFeeds.length >= 10) return newsFeeds
            const [authorId, postId] = this.posts[i]
            if(!myFollowers.has(authorId)) continue
            newsFeeds.push(postId)
        }
        return newsFeeds
    }
    follow(followerId: number, followeeId: number): void {
        if(!this.followStatus.has(followerId)) this.followStatus.set(followerId, new Set([followerId]))
        const followers = this.followStatus.get(followerId)
        followers.add(followeeId)
    }
    unfollow(followerId: number, followeeId: number): void {
        if(!this.followStatus.has(followerId)) return
        const followers = this.followStatus.get(followerId)
        followers.delete(followeeId)
    }
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글