buildTree 3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
buildCommentTree = (data)->
# main = x for x in data when not x.parent?
main = data.filter (x) -> not x.parent?
comments_by_id = {}
for obj in data when obj.id?
comments_by_id[obj.id] = obj
recursiveFetchChildren = (children) ->
if children.length == 0
return
level = []
for x in children
comment = comments_by_id[x]
if comment.children.length > 0
children_of_child = recursiveFetchChildren comment.children
if children_of_child
comment.children = children_of_child
else
comment.children = null
level.push comment
level
result = []
for comment in main
chield_comments = recursiveFetchChildren comment.children
comment.children = null
if chield_comments
comment.children = chield_comments
result.push comment
result