fix: improve building comment tree (#40)

As we build the map of nodes, keep track of the minimum depth level.
Afterwards, nodes at the minimum depth level go into the tree as the
roots.

We no longer need to check if the tree belongs to a parent comment or
not.

Fixes #36 more.
This commit is contained in:
Peter Bui authored and GitHub committed 2023-07-28 20:37:44 -07:00
1 parent 590eedc0fb
commit 9eb3665fa7
2 files changed
+10 -17

No files matched your search

@@ -59,7 +59,7 @@
return return
} }
const tree = buildCommentsTree(newComments.comments, false) const tree = buildCommentsTree(newComments.comments, parent.depth)
// 0.18.2 -> 0.18.3 broke this // 0.18.2 -> 0.18.3 broke this
// so i'm adding this check // so i'm adding this check
+9 -16
View File
@@ -24,31 +24,29 @@ function getDepthFromComment(comment?: Comment): number | undefined {
export function buildCommentsTree( export function buildCommentsTree(
comments: CommentView[], comments: CommentView[],
parentComment: boolean,
baseDepth: number = 0 baseDepth: number = 0
): CommentNodeI[] { ): CommentNodeI[] {
const map = new Map<number, CommentNodeI>() const map = new Map<number, CommentNodeI>()
const depthOffset = !parentComment
? 0
: getDepthFromComment(comments[0].comment) ?? 0
let min_depth = Number.MAX_VALUE
for (const comment_view of comments) { for (const comment_view of comments) {
const depthI = getDepthFromComment(comment_view.comment) ?? 0 const depthI = getDepthFromComment(comment_view.comment) ?? 0
const depth = depthI ? depthI - depthOffset : 0 const depth = depthI + baseDepth
const node: CommentNodeI = { const node: CommentNodeI = {
comment_view, comment_view,
children: [], children: [],
depth: depth + baseDepth, depth: depth,
} }
min_depth = Math.min(min_depth, depth)
map.set(comment_view.comment.id, { ...node }) map.set(comment_view.comment.id, { ...node })
} }
const tree: CommentNodeI[] = [] const tree: CommentNodeI[] = []
// if its a parent comment fetch, then push the first comment to the top node. // push all nodes at the minimum depth to the top of the tree
if (parentComment) { for (const comment_view of comments) {
const cNode = map.get(comments[0].comment.id) const cNode = map.get(comment_view.comment.id)
if (cNode) { if (cNode && cNode.depth == min_depth) {
tree.push(cNode) tree.push(cNode)
} }
} }
@@ -63,10 +61,6 @@ export function buildCommentsTree(
if (parent) { if (parent) {
parent.children.push(child) parent.children.push(child)
} }
} else {
if (!parentComment) {
tree.push(child)
}
} }
} }
} }
@@ -120,9 +114,8 @@ export function insertCommentIntoTree(
export async function buildCommentsTreeAsync( export async function buildCommentsTreeAsync(
comments: CommentView[], comments: CommentView[],
parentComment: boolean
) { ) {
const result = buildCommentsTree(comments, parentComment) const result = buildCommentsTree(comments)
return result return result
} }