I have an ordered list in this format. The data is ordered by path so that the list will never contain a child before the parent in the list.
id, path
1, null
2, null
3, 1
4, 1-3
5, 2
6, 2-5
Each entry contains the path it needs to place itself in the tree structure.
The catch is that the list doesn't always start with nulls sometimes the list starts in the middle of a path.
id, path
10, 2-5-6
11, 2-5-6-10
12, 2-5-6-10
13, 2-5-6-10-11
14, 2-5-6-10-11-13
15, 2-5-6-10-12
In this case I need to treat the first record in this list as the root and build out everything else as normal without permanently editing the paths of any items in the list.
function nestComments(comments) {
var nested = {
"Comments": []
};
if (!comments) return nested;
var normalize,
path,
level;
for (var i = 0; i < comments.length; i++) {
var comment = comments[i],
tree = nested,
isValid = true;
if (comment.path) {
path = comment.path.split('-');
//permalinked comments don't have null paths
//keep track of the permalink the path
//adjust children paths to treat permalink path like the root
//if the first comment has a path then we need to normalize the path
if (i === 0) {
normalize = path.length;
}
if (normalize) {
//normalize the path based on the peramlink's path
path.splice(0, normalize);
}
for (var j = 0; j < path.length; j++) {
var step = path[j];
var index = tree.Comments.findIndex(x => x.comment_id.toString() === step);
if (index < 0) {
isValid = false;
break;
}
tree = tree.Comments[index];
tree.Comments = tree.Comments || [];
}
}
if (!path || path.length === 0) {
level = 0;
} else {
level = path.findIndex(x => x === path[path.length - 1]);
}
if (!trimComments(level, tree) || !isValid) {
continue;
}
tree.Comments.push(comment);
}
return nested;
}
function trimComments(level, tree) {
var result;
switch (level) {
case 0:
result = true; // limit based on the sql query
break;
case 1:
result = tree.Comments.length < 5;
break;
case 2:
result = tree.Comments.length < 5;
break;
case 3:
result = tree.Comments.length < 3;
break;
case 4:
result = tree.Comments.length < 2;
break;
case 5:
result = tree.Comments.length < 1;
break;
case 6:
result = tree.Comments.length < 1;
break;
default:
result = false;
break;
}
return result;
}
var comments = nestComments([{comment_id: 4, path:"1-2-3"},{comment_id: 5, path:"1-2-3-4"},{comment_id: 6,path:"1-2-3-4"}, {comment_id: 7, path:"1-2-3-4-6"},{comment_id: 8, path:"1-2-3-4-6"}, {comment_id: 9, path:"1-2-3-4-6-7"}, {comment_id: 10, path:"1-2-3-4-6-7-9"}, {comment_id: 11, path:"1-2-3-4-6-8"}]);
console.log(comments);
Please help me improve this code.