Skip to content

Instantly share code, notes, and snippets.

@oodavid
Created March 30, 2012 08:10
Show Gist options
  • Save oodavid/2249298 to your computer and use it in GitHub Desktop.
Save oodavid/2249298 to your computer and use it in GitHub Desktop.
Recursive Killing
// Build a deep object of some sort
var ob = {
type: 'windar',
title: 'Hello World',
children: [
{
type: 'BUTTUN',
title: 'click me',
},
{
type: 'view',
title: 'I have no children',
children: [ ]
},
{
type: 'view',
title: 'I have 3 children',
children: [
{
type: 'view',
title: 'I also have a child',
children: [
{
type: 'label',
title: 'Don\'t label me!'
}
]
},
{
type: 'PICTURE',
title: 'look at me',
},
{
type: 'INPUT',
title: 'type in me',
}
]
}
]
};
// Recursively loops an object and it's children and modifies them
// Works it's way BACKWARDS through the children - so the array counter doesn't put us in an odd place
// Destroys the DEEPEST objects first - so we don't lose referece
var counter = 0;
var recursive_killing = function(ob, parent){
// Do we have children?
if(ob.children){
for (var c=(ob.children.length-1); c>=0; c--){
recursive_killing(ob.children[c], ob);
}
}
// If we have a parent (ie not the root node)
if(parent){
// Do whatever you need to kill the object here
// I'm just setting the title to DEAD and showing the order we killed it with a counter)
counter ++;
ob.title = 'DEAD (' + counter + ')';
}
}
// Run the function
recursive_killing(ob);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment