|
|
import { getElementParent } from "./querying.js"; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function cacheParentResults(next, { adapter, cacheResults }, matches) { |
|
|
if (cacheResults === false || typeof WeakMap === "undefined") { |
|
|
return (elem) => next(elem) && matches(elem); |
|
|
} |
|
|
|
|
|
|
|
|
const resultCache = new WeakMap(); |
|
|
function addResultToCache(elem) { |
|
|
const result = matches(elem); |
|
|
resultCache.set(elem, result); |
|
|
return result; |
|
|
} |
|
|
return function cachedMatcher(elem) { |
|
|
if (!next(elem)) |
|
|
return false; |
|
|
if (resultCache.has(elem)) { |
|
|
return resultCache.get(elem); |
|
|
} |
|
|
|
|
|
let node = elem; |
|
|
do { |
|
|
const parent = getElementParent(node, adapter); |
|
|
if (parent === null) { |
|
|
return addResultToCache(elem); |
|
|
} |
|
|
node = parent; |
|
|
} while (!resultCache.has(node)); |
|
|
return resultCache.get(node) && addResultToCache(elem); |
|
|
}; |
|
|
} |
|
|
|