Skip to content

Instantly share code, notes, and snippets.

@nasrulfuad
Created June 12, 2022 12:17
Show Gist options
  • Save nasrulfuad/2434e4d687449fa7c3f46c9ede50a901 to your computer and use it in GitHub Desktop.
Save nasrulfuad/2434e4d687449fa7c3f46c9ede50a901 to your computer and use it in GitHub Desktop.
Function to nesting comments in typescript
/**
* Examples :
* [
* { id: 1, text: 'Hello', replyToId: null, },
* { id: 2, text: 'Hi', replyToId: 1, },
* { id: 3, text: 'Hello World', replyToId: 2, },
* ]
*
* ======== TO ========
*
* [
* {
* id: 1,
* text: 'Hello',
* replyToId: null,
* replies: [
* {
* id: 2,
* text: 'Hi',
* replyToId: 1,
* replies: [
* {
* id: 3,
* text: 'Hello World',
* replyToId: 2,
* }
* ]
* }
* ]
* },
* ]
*/
type TComment = {
id: number;
text: string;
replyToId: TComment["id"] | null;
replies?: TComment[];
}
/**
* Nesting comments
* @param comments TComment
* @returns TComment[]
*/
function nest<T extends TComment> (comments: T[]) {
if (comments.length === 0) {
return comments
};
return comments.reduce<T[]>((nested, comment) => {
comment.replies = comments.filter(
reply => reply.replyToId === comment.id
);
nest(comment.replies);
if (comment.replyToId == null) {
nested.push(comment);
}
return nested
}, []);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment