mr*********@yahoo.co.in (Mriganka) writes:
I want to create a hierarchical tree from the array of strings
obtained by extracting a jar file.I want to do this using Javascript.
For ex,
I am having the entries in the array as
com/asd/many/a.class
com/asd/many/b.class
com/asd/xyz/c.class
com/asd/d.class
com/asd/man/you/e.class
Ok, format is simple. Do you expect to have only one root, or several?
If only "com" exists at the top level, you will get just a tree,
otherwise you get a forest.
These are obtained by extracting any jar file.
Whatever :)
I want to create the tree using this information.
Please send me the required algorithm or the source code as soon as
possible.
The algorithm is easy. Split each string at the slashes, and build
a tree structure dynamically. Each node is an array, where the integer
indexed elements are the leaves and non-integer indexed elements are
branches to other tree nodes.
---
function plant(seed) { // seed is an array of strings
var forest = new Array();
for (var i=0; i<seed.length;i++) {
var path = seed[i].split("/");
var node = forest;
for(var j=0; j<path.length-1;j++) { // follow path, ot build it
var branchName = path[j];
var childNode = node[branchName];
if (!childNode) {
childNode = node[branchName] = new Array();
}
node = childNode;
}
node[node.length] = path[path.length-1];
}
return forest;
}
---
Your example strings would generate a structure similar to this
object literal (except it uses arrays, not objects):
---
{com: {asd: { many: { "0": "a.class",
"1": "b.class" },
xyz: { "0" : "c.class" },
"0": "d.class",
man: { you: { "0" : "e.class" }}}}}
---
/L
--
Lasse Reichstein Nielsen -
lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'