Christopher A. Kelly wrote:
i need a script that will take a collection of strings eg:
inbox
inbox/folder-1
inbox/folder-1/Subfolder1
trash
sent and turns it into
root <static, added elsewhere
|_inbox
| |_folder-1
| |_subfolder-1
|_sent
Quick hack:
/**
* Allows for setting a property of an property.
*
* @author
* (C) 2004 Thomas Lahn <ob*******@PointedEars.de>
* Distributed under the terms of the GNU GPL v2.
* @argument object oRoot
* Reference to the object which owns the property
* which property's value should be set.
* @argument string sPropertyPath
* @{(value)}-delimited path of property names.
* @optional _ value = undefined
* Value to assign to the nested property.
* @optional string|RegExp delimiter = "/"
* Delimiter used to split @{(sPropertyPath)} into
* path components.
*/
function setNestedProperty(oRoot, sPropertyPath, value, delimiter)
{
if (!delimiter)
{
delimiter = "/";
}
var aPropertyPath = sPropertyPath.split(delimiter);
for (var i = 0, len = aPropertyPath.length - 1; i < len; i++)
{
var
sComponent = aPropertyPath[i],
t, m = o.hasOwnProperty,
bMethod = ((t = typeof m) == "function"
|| (t == "object" && m));
if ((bMethod && !o.hasOwnProperty(sComponent)
|| (!bMethod && o[sComponent] == "undefined"))
{
oRoot[sComponent] = {};
}
oRoot = oRoot[sComponent];
}
oRoot[aPropertyPath[len]] = value;
}
var oTree = {};
for (var aTree = ['inbox', 'inbox/folder-1', 'inbox/folder-1/Subfolder1',
'trash'],
i = 0,
len = aTree.length;
i < len;
i++)
{
setNestedProperty(oTree, aTree[i].split('/').join('/ '), {});
}
This should create an object with the following structure:
var oTree = {
' inbox': {
' folder-1': {
' subfolder-1': {}
}
},
' sent': {}
}
The leading space should prevent built-in prototype properties from being
accidentally overlayed. Can be optimized if only the leaves are iterated
as iterating a leaf will automagically create its superordinate nodes.
Displaying this object as a tree is left as an exercise to the reader.
PointedEars
--
This isn't Mission Difficult, Mr. Hunt, it's Mission Impossible