54 lines
865 B
JavaScript
54 lines
865 B
JavaScript
var _ = require('lodash');
|
|
|
|
// Tree manipulation helpers
|
|
|
|
exports.walk = function(branch, func, parent) {
|
|
|
|
if(!branch) return;
|
|
|
|
var breakHere = func(branch, parent);
|
|
|
|
if(breakHere) return breakHere;
|
|
|
|
var items = branch.items;
|
|
|
|
if(!items) return;
|
|
|
|
for( var i = 0, item = items[i]; (item = items[i]); i++ ) {
|
|
breakHere = exports.walk(item, func, branch);
|
|
if(breakHere) return breakHere;
|
|
}
|
|
|
|
};
|
|
|
|
exports.find = function(tree, obj) {
|
|
|
|
var result;
|
|
|
|
exports.walk(tree, function(item, parent) {
|
|
if( _.isEqual(item, obj) ) {
|
|
result = {item: item, parent: parent};
|
|
return true;
|
|
}
|
|
});
|
|
|
|
return result;
|
|
|
|
};
|
|
|
|
exports.matches = function(tree, obj) {
|
|
|
|
var results = [];
|
|
|
|
var matches = _.matches(obj);
|
|
|
|
exports.walk(tree, function(item) {
|
|
if( matches(item) ) {
|
|
results.push(item);
|
|
}
|
|
});
|
|
|
|
return results;
|
|
|
|
};
|