42 lines
988 B
JavaScript
42 lines
988 B
JavaScript
/**
|
|
* @typedef {import('$types/base').Comment} Comment
|
|
*/
|
|
|
|
/**
|
|
* @param {import('$types/base').Result<Comment>} comments
|
|
* @returns {import('$types/base').CommentTreeNode[]}
|
|
*/
|
|
export function buildCommentTree(comments) {
|
|
/** @type {Comment[]} */
|
|
let roots = [];
|
|
/** @type {Map<number, Comment[]>} */
|
|
let refs = new Map();
|
|
|
|
comments.forEach((comment, id) => {
|
|
if (comment.parentCommentId == null) {
|
|
roots.push(comment);
|
|
} else {
|
|
if (!refs.has(comment.parentCommentId)) {
|
|
refs.set(comment.parentCommentId, []);
|
|
}
|
|
refs.get(comment.parentCommentId)?.push(comment);
|
|
}
|
|
});
|
|
|
|
return roots.map(r => buildFromRoot(refs, r));
|
|
}
|
|
|
|
/**
|
|
* @param {Map<number, Comment[]>} refs
|
|
* @param {Comment} comment
|
|
* @returns {import('$types/base').CommentTreeNode}
|
|
*/
|
|
function buildFromRoot(refs, comment) {
|
|
return {
|
|
parent: comment,
|
|
children: refs.get(comment.id)?.map(c => {
|
|
return buildFromRoot(refs, c);
|
|
}) || []
|
|
}
|
|
}
|