cache.js 1.7 KB

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