aboutsummaryrefslogtreecommitdiffstats
path: root/src/services/graphql/helpers/build-comments-tree.ts
blob: 1534cfe5ead8776e204056626ebb9f109f4d5995 (plain)
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
import type { SingleComment } from '../../../types';

/**
 * Create a comments tree with replies.
 *
 * @param {SingleComment[]} comments - A flatten comments list.
 * @returns {SingleComment[]} An array of comments with replies.
 */
export const buildCommentsTree = (
  comments: SingleComment[]
): SingleComment[] => {
  type CommentsHashTable = Record<string, SingleComment>;

  const hashTable: CommentsHashTable = Object.create(null);
  const commentsTree: SingleComment[] = [];

  comments.forEach((comment) => {
    hashTable[comment.id] = { ...comment, replies: [] };
  });

  comments.forEach((comment) => {
    if (comment.parentId) {
      hashTable[comment.parentId].replies.push(hashTable[comment.id]);
    } else {
      commentsTree.push(hashTable[comment.id]);
    }
  });

  return commentsTree;
};