Created
June 12, 2022 12:17
-
-
Save nasrulfuad/2434e4d687449fa7c3f46c9ede50a901 to your computer and use it in GitHub Desktop.
Function to nesting comments in typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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