/**
* Comment service for building nested comment trees
*/
import type { HackerNewsPost } from "../types/index.js";
/**
* Build nested comment tree from flat comment list
*
* Note: HN API returns posts with children already nested,
* but this function can reconstruct trees if needed
*/
export function buildCommentTree(post: HackerNewsPost): HackerNewsPost {
// If the post already has children, it's already a tree
if (post.children && post.children.length > 0) {
// Recursively process nested children
post.children = post.children.map((child) => buildCommentTree(child));
}
return post;
}
/**
* Calculate comment count recursively
*/
export function countComments(post: HackerNewsPost): number {
if (!post.children || post.children.length === 0) {
return 0;
}
let count = post.children.length;
for (const child of post.children) {
count += countComments(child);
}
return count;
}
/**
* Calculate maximum nesting depth
*/
export function calculateNestingDepth(post: HackerNewsPost, currentDepth = 0): number {
if (!post.children || post.children.length === 0) {
return currentDepth;
}
let maxDepth = currentDepth;
for (const child of post.children) {
const childDepth = calculateNestingDepth(child, currentDepth + 1);
maxDepth = Math.max(maxDepth, childDepth);
}
return maxDepth;
}