Skip to content

Instantly share code, notes, and snippets.

@meltingice
Created May 23, 2017 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meltingice/c80bc5eb8088e720bff668523c070bc7 to your computer and use it in GitHub Desktop.
Save meltingice/c80bc5eb8088e720bff668523c070bc7 to your computer and use it in GitHub Desktop.
# In order to build the tree structure, we select comments that are only root nodes,
# i.e. comments that are not a reply. From there, we can build the tree structure based
# on their children, which we collected earlier.
transform_node_index(node_index.select { |node_id, data| data[:parent].nil? }.values)
# This is a recursive method that will traverse the comment structure, and run for
# the children of each comment. In the end, once the recursion finishes, a tree pops out.
def transform_node_index(nodes)
nodes.map do |data|
{
comment: data[:node],
reply_to: data[:reply_to],
children: transform_node_index(data[:children])
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment