Skip to content

Instantly share code, notes, and snippets.

/trycf-gist.cfm

Created Aug 29, 2016
Embed
What would you like to do?
TryCF Gist
<cfscript>
TestData = querynew("id,parentId,nodeText");
queryAddRow(TestData,{id:1,nodeText:"File" });
queryAddRow(TestData,{id:2,nodeText:"New",parentId:1});
queryAddRow(TestData,{id:3,nodeText:"File",parentId:2});
queryAddRow(TestData,{id:4,nodeText:"Folder",parentId:2});
queryAddRow(TestData,{id:5,nodeText:"Edit"});
queryAddRow(TestData,{id:6,nodeText:"Copy",parentId:5});
queryAddRow(TestData,{id:7,nodeText:"Cut",parentId:5});
queryAddRow(TestData,{id:8,nodeText:"Paste",parentId:5});
queryAddRow(TestData,{id:9,nodeText:"Help"});
queryAddRow(TestData,{id:10,nodeText:"About",parentId:9});
/**
* Convert a hierarchical dataset into a nested tree
* structure
*/
function toNestedSet(query data) {
// reduce the query to an array of nodes
return data.reduce(function (stacks, curRow, idx, data) {
// use stacks to track the result and branch positions
stacks = stacks ?: {
result = []
,branch = []
,lastNode = javaCast("null","")
};
// this is the actual data node
var newNode = {
nodeText: curRow.nodeText
};
var branchSize = stacks.branch.len();
// encountering a "top-level" record resets the branch
// stack and pushes the new node onto the result stack
if (curRow.parentId == "") {
stacks.lastNode = newNode;
stacks.branch = [];
stacks.result.add(newNode);
// the current node references a parent - scan the
// branch stack for the parent (we're assuming the
// dataset is sorted)
} else if (branchSize) {
// scan the branch stack for the correct parent
while ( branchSize
&& stacks.branch[branchSize].id != curRow.parentId
) {
stacks.branch.deleteAt(branchSize--);
}
// mark the parent as the "current" node
stacks.lastNode = stacks.branch[branchSize].node;
// create the children array as needed
if (!stacks.lastNode.keyExists("children"))
stacks.lastNode.children = [];
// add the child node
stacks.lastNode.children.add(newNode);
}
// always add the new node to the current branch
stacks.branch.add({
node: newNode
,id: curRow.id
});
// mark the last node operated on
stacks.lastNode = newNode;
// if this is the last iteration return the result
return idx == data.recordcount ? stacks.result : stacks;
});
}
writedump(toNestedSet(TestData, "parentId"));
</cfscript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.