Created
August 2, 2017 11:42
-
-
Save lunaroyster/ff573edfeadc0e5ea26c37d21c54d5f1 to your computer and use it in GitHub Desktop.
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
var toTree = function(comments) { | |
comments.sort(function(x, y) {return -(x.degree-y.degree)}) //Sorts by degree, descending. | |
var treeDegree = comments[0].degree; //Max degree | |
var commentsByDegree = {}; | |
for(var comment of comments) { | |
//Separates comments by degree. | |
comment.comments = []; | |
if(commentsByDegree.hasOwnProperty(comment.degree)) { | |
commentsByDegree[comment.degree].push(comment); | |
} | |
else { | |
commentsByDegree[comment.degree] = [comment]; | |
} | |
} | |
for(var i = treeDegree-1; i >=0; i--) { | |
//For each degree, starting from the second last, all the way to zero | |
for(var comment of commentsByDegree[i+1]) { | |
//We look one by one at the comments in the higher degree | |
for(var parentComment of commentsByDegree[i]) { | |
//And if they have a 'parent' field in one of the comments | |
if(comment.parent != parentComment._id) continue; | |
//We add them as a child comment. | |
parentComment.comments.push(comment) | |
} | |
} | |
} | |
//At the end, the array at degree zero contains the full comment tree. | |
return commentsByDegree[0]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment