It's probably just the "Friday after 5:00 and I want to go home" effect, but I'm stumped on this problem. I have a recursive iterator method I'll call each:
function canIterate(obj) {
return (obj && (typeof obj === 'object' || Array.isArray(obj)));
}
function each(obj, onSuccess, recursive) {
if (canIterate(obj)) {
Object.keys(obj).forEach(function(key) {
var val = obj[key];
if (onSuccess && val && key) {
var quit = onSuccess(val, key);
if (false === quit) {
return false;
}
}
if (true === recursive) {
each(val, onSuccess, true);
}
});
}
}
This is quite slow on large sets of data (I'll explain below). As @raganwald explains here, Trampolines are the solution to the problem.. My question is: how do I refactor this recursive function to utilize the trampoline technique?
So I have a polling mechanism to request the current state of a tree, in this case it's a location tree which looks something like:
Hospital Campus Main
Main Building
Radiology Department
Lab 1
Lab 2
MRI Lab
Machine Cabinets
Spare Parts Shelf
The Tree renders in a grid of things that belong to locations, and for each row in the grid that has a location, I need to render the tree setting the root to the location for this row. So if we had:
Part | Location | Tree
widget MRI Lab MRI Lab > Machine Cabinets > Spare Parts Shelf
So never mind that some or all of this could be handled on the server side--I'll optimize performance of the data fetch later.
Is there an efficient way to rewrite my each method to use the Trampoline or CPS style?