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:
1 parent
590eedc0fb
commit
9eb3665fa7
2 files changed
+10
-17
No files matched your search
@@ -59,7 +59,7 @@
|
||||
return
|
||||
}
|
||||
|
||||
const tree = buildCommentsTree(newComments.comments, false)
|
||||
const tree = buildCommentsTree(newComments.comments, parent.depth)
|
||||
|
||||
// 0.18.2 -> 0.18.3 broke this
|
||||
// so i'm adding this check
|
||||
|
||||
@@ -24,31 +24,29 @@ function getDepthFromComment(comment?: Comment): number | undefined {
|
||||
|
||||
export function buildCommentsTree(
|
||||
comments: CommentView[],
|
||||
parentComment: boolean,
|
||||
baseDepth: number = 0
|
||||
): 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) {
|
||||
const depthI = getDepthFromComment(comment_view.comment) ?? 0
|
||||
const depth = depthI ? depthI - depthOffset : 0
|
||||
const depth = depthI + baseDepth
|
||||
const node: CommentNodeI = {
|
||||
comment_view,
|
||||
children: [],
|
||||
depth: depth + baseDepth,
|
||||
depth: depth,
|
||||
}
|
||||
min_depth = Math.min(min_depth, depth)
|
||||
map.set(comment_view.comment.id, { ...node })
|
||||
}
|
||||
|
||||
const tree: CommentNodeI[] = []
|
||||
|
||||
// if its a parent comment fetch, then push the first comment to the top node.
|
||||
if (parentComment) {
|
||||
const cNode = map.get(comments[0].comment.id)
|
||||
if (cNode) {
|
||||
// push all nodes at the minimum depth to the top of the tree
|
||||
for (const comment_view of comments) {
|
||||
const cNode = map.get(comment_view.comment.id)
|
||||
if (cNode && cNode.depth == min_depth) {
|
||||
tree.push(cNode)
|
||||
}
|
||||
}
|
||||
@@ -63,10 +61,6 @@ export function buildCommentsTree(
|
||||
if (parent) {
|
||||
parent.children.push(child)
|
||||
}
|
||||
} else {
|
||||
if (!parentComment) {
|
||||
tree.push(child)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,9 +114,8 @@ export function insertCommentIntoTree(
|
||||
|
||||
export async function buildCommentsTreeAsync(
|
||||
comments: CommentView[],
|
||||
parentComment: boolean
|
||||
) {
|
||||
const result = buildCommentsTree(comments, parentComment)
|
||||
const result = buildCommentsTree(comments)
|
||||
|
||||
return result
|
||||
}
|
||||
Reference in new issue
Block a user