I have a problem with dereferencing a Javascript object and setting it to NULL.
Here, I have a Folder implementation that supports recursive subdirectory removal. Please see my comments to understand my dilemma.
function Folder(name, DOM_rows) {
this.name = name;
this.files = [].concat(DOM_rows);
this.subdirs = [];
}
Folder.prototype.AddDir(name, DOM_rows) {
this.subdirs.push(new Folder(name, DOM_rows));
}
Folder.prototype.RemoveDir(folder) {
var stack = [folder];
while(stack.length > 0) {
var cur = stack.pop();
// do a post-order depth-first traversal, so dig to the deepest subdir:
if(cur.subdirs.length > 0) {
while(cur.subdirs.length > 0) { stack.push(cur.subdirs.pop()); }
} else {
// arrived at a leaf-level:
cur.files = null;
// now how do I delete cur from it's parent's subdirs array?
// the only way I know how is to keep a "cur.parentDir" reference,
// then find parent.subdirs[ index of cur ] and slice it out.
// How can I do the JS-equivalent of *cur = NULL?
}
}
}
Note that you don’t have as big a problem as you suspect, since all subdirectories but
folderin yourRemoveDirwill be deleted from their parent’ssubdirby thestack.push(cur.subdirs.pop());lineTo find a subdirectory in a parent, you could make use an object-as-dictionary rather than an array for
subdirs:Given a folder, you can remove the folder from the parent with:
Here’s a preorder version:
And the recursive post-order version:
And the iterative post-order version:
Though, unless you need to take additional steps when processing deleted files & folders, a simple:
should suffice.