Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add esquery.traverse #45

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions esquery.js
Original file line number Diff line number Diff line change
Expand Up @@ -245,32 +245,45 @@
}

/**
* From a JS AST and a selector AST, collect all JS AST nodes that match the selector.
* From a JS AST and a selector AST, visit all JS AST nodes that match the selector.
*/
function match(ast, selector) {
var ancestry = [], results = [], altSubjects, i, l, k, m;
if (!selector) { return results; }
function traverse(ast, selector, visitor) {
var ancestry = [], altSubjects, i, l, k, m;
if (!selector) { return }
altSubjects = subjects(selector);
estraverse.traverse(ast, {
enter: function (node, parent) {
if (parent != null) { ancestry.unshift(parent); }
if (matches(node, selector, ancestry)) {
if (altSubjects.length) {
for (i = 0, l = altSubjects.length; i < l; ++i) {
if (matches(node, altSubjects[i], ancestry)) { results.push(node); }
if (matches(node, altSubjects[i], ancestry)) {
visitor(node, parent, ancestry.slice());
}
for (k = 0, m = ancestry.length; k < m; ++k) {
if (matches(ancestry[k], altSubjects[i], ancestry.slice(k + 1))) {
results.push(ancestry[k]);
visitor(ancestry[k], parent, ancestry.slice());
}
}
}
} else {
results.push(node);
visitor(node, parent, ancestry.slice());
}
}
},
leave: function () { ancestry.shift(); }
});
}

/**
* From a JS AST and a selector AST, collect all JS AST nodes that match the selector.
*/
function match(ast, selector) {
var results = [];
if (!selector) { return results; }
traverse(ast, selector, function(node, parent, ancestry){
results.push(node);
})
return results;
}

Expand All @@ -290,6 +303,7 @@

query.parse = parse;
query.match = match;
query.traverse = traverse;
query.matches = matches;
return query.query = query;
}
Expand Down