1 import { getCommentParentId, getDepthFromComment } from "@utils/app";
2 import { CommentView } from "lemmy-js-client";
3 import { CommentNodeI } from "../../interfaces";
5 export default function buildCommentsTree(
6 comments: CommentView[],
7 parentComment: boolean,
9 const map = new Map<number, CommentNodeI>();
10 const depthOffset = !parentComment
12 : getDepthFromComment(comments[0].comment) ?? 0;
14 for (const comment_view of comments) {
15 const depthI = getDepthFromComment(comment_view.comment) ?? 0;
16 const depth = depthI ? depthI - depthOffset : 0;
17 const node: CommentNodeI = {
22 map.set(comment_view.comment.id, { ...node });
25 const tree: CommentNodeI[] = [];
27 // if its a parent comment fetch, then push the first comment to the top node.
29 const cNode = map.get(comments[0].comment.id);
35 for (const comment_view of comments) {
36 const child = map.get(comment_view.comment.id);
38 const parent_id = getCommentParentId(comment_view.comment);
40 const parent = map.get(parent_id);
41 // Necessary because blocked comment might not exist
43 parent.children.push(child);