Sometimes it is necessary to remove all or at least many elements that are contained in a container element, for example cut-sets from a saved analysis model, or events from a fault tree or hazardous events from a HARA/FHA.
Deletion should always be done using the Trashbin, but besides that, there is another pitfall that should be known to scripters. Lets have a look at this simple example of a deletion method that removes all sub-packages of a package:
// $EXPERIMENTAL$
load(".lib/trashbin.js");
// just iterate and delete
var children = selection[0].nestedPackages;
for (var i = 0; i < children.size(); i++) {
Trashbin.deleteElement(children.get(i));
}
console.log("Done");
It looks pretty okay but when executed on this sample package:

... the result will be this:

What has happened? Deleting an element will ultimately also modify the collection of the container element, that means after the first element was deleted, the collection only contains 3 elements, and the second element becomes the first. So index i is not really correct anymore.
One option to solve that would be to always deleted "from the tail":
// just iterate from behind and delete
var children = selection[0].nestedPackages;
for (var i = children.size()-1; i >=0 ; i--) {
Trashbin.deleteElement(children.get(i));
}
That way, only the last element is removed with each step, shrinking the collection has no effect on the remaining part and the index.
Other (easiest) option is to convert the list to an array first:
// just iterate over an array (copy) and delete
var children = selection[0].nestedPackages.toArray();
for (var i = 0; i < children.length; i++) {
Trashbin.deleteElement(children[i]);
}
Hope that helps to improve some of your scripts.
Jan