/** * @typedef {import('$types/base').Comment} Comment */ /** * @param {import('$types/base').Result} comments * @returns {import('$types/base').CommentTreeNode[]} */ export function buildCommentTree(comments) { /** @type {Comment[]} */ let roots = []; /** @type {Map} */ 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} 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); }) || [] } }