diff --git a/esquery.js b/esquery.js index 715919e..3f703d8 100644 --- a/esquery.js +++ b/esquery.js @@ -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. @@ -89,7 +110,7 @@ const MATCHER_CACHE = typeof WeakMap === 'function' ? new WeakMap : null; */ function getMatcher(selector) { if (selector == null) { - return () => true; + return truelyMatcher; } if (MATCHER_CACHE != null) { @@ -97,12 +118,12 @@ function getMatcher(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)); } /**