cache.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { getElementParent } from "./querying.js";
  2. /**
  3. * Some selectors such as `:contains` and (non-relative) `:has` will only be
  4. * able to match elements if their parents match the selector (as they contain
  5. * a subset of the elements that the parent contains).
  6. *
  7. * This function wraps the given `matches` function in a function that caches
  8. * the results of the parent elements, so that the `matches` function only
  9. * needs to be called once for each subtree.
  10. */
  11. export function cacheParentResults(next, { adapter, cacheResults }, matches) {
  12. if (cacheResults === false || typeof WeakMap === "undefined") {
  13. return (elem) => next(elem) && matches(elem);
  14. }
  15. // Use a cache to avoid re-checking children of an element.
  16. // @ts-expect-error `Node` is not extending object
  17. const resultCache = new WeakMap();
  18. function addResultToCache(elem) {
  19. const result = matches(elem);
  20. resultCache.set(elem, result);
  21. return result;
  22. }
  23. return function cachedMatcher(elem) {
  24. if (!next(elem))
  25. return false;
  26. if (resultCache.has(elem)) {
  27. return resultCache.get(elem);
  28. }
  29. // Check all of the element's parents.
  30. let node = elem;
  31. do {
  32. const parent = getElementParent(node, adapter);
  33. if (parent === null) {
  34. return addResultToCache(elem);
  35. }
  36. node = parent;
  37. } while (!resultCache.has(node));
  38. return resultCache.get(node) && addResultToCache(elem);
  39. };
  40. }
  41. //# sourceMappingURL=cache.js.map