From 712ea2994d5797a1febac3303c4eb43c9a54de07 Mon Sep 17 00:00:00 2001 From: krawieck Date: Mon, 31 Aug 2020 01:46:47 +0200 Subject: [PATCH] Add CommentTree #16 `CommentTree` transforms `List` of `CommentView`s into a tree-like structure --- lib/widgets/comment_tree.dart | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 lib/widgets/comment_tree.dart diff --git a/lib/widgets/comment_tree.dart b/lib/widgets/comment_tree.dart new file mode 100644 index 0000000..d0da0da --- /dev/null +++ b/lib/widgets/comment_tree.dart @@ -0,0 +1,33 @@ +import 'package:lemmy_api_client/lemmy_api_client.dart'; + +class CommentTree { + CommentView comment; + List children; + + CommentTree(this.comment, [this.children]) { + children ??= []; + } + + static List fromList(List comments) { + CommentTree gatherChildren(CommentTree parent) { + for (var el in comments) { + if (el.parentId == parent.comment.id) { + parent.children.add(gatherChildren(CommentTree(el))); + } + } + return parent; + } + + var parents = []; + + // first pass to get all the parents + for (var i = 0; i < comments.length; i++) { + if (comments[i].parentId == null) { + parents.add(CommentTree(comments[i])); + } + } + + var result = parents.map(gatherChildren).toList(); + return result; + } +}