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 matcher with a gurd wrapper. (#135) #137

Closed
wants to merge 2 commits 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
27 changes: 24 additions & 3 deletions esquery.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,27 @@ function inPath(node, ancestor, path, fromPathIndex) {
*/
const MATCHER_CACHE = typeof WeakMap === 'function' ? new WeakMap : null;

// constant for truely matcher
const truelyMatcher = () => true;

/**
* A gurd helper for mather with some preflight assets
*
* @param {SelectorMatcher} matcher
* @returns {SelectorMatcher}
*/
const matcherGurd = (matcher) => {
return (node, ancestry, ...args) => {
if (!node) {
return false;
}
if (!ancestry) {
ancestry = [];
}
return matcher(node, ancestry, ...args);
};
};

/**
* Look up a matcher function for `selector` in the cache.
* If it does not exist, generate it with `generateMatcher` and add it to the cache.
Expand All @@ -89,20 +110,20 @@ const MATCHER_CACHE = typeof WeakMap === 'function' ? new WeakMap : null;
*/
function getMatcher(selector) {
if (selector == null) {
return () => true;
return truelyMatcher;
}

if (MATCHER_CACHE != null) {
let matcher = MATCHER_CACHE.get(selector);
if (matcher != null) {
return matcher;
}
matcher = generateMatcher(selector);
matcher = matcherGurd(generateMatcher(selector));
MATCHER_CACHE.set(selector, matcher);
return matcher;
}

return generateMatcher(selector);
return matcherGurd(generateMatcher(selector));
}

/**
Expand Down