Skip to content

Commit

Permalink
feat(general): Add cacheResults option
Browse files Browse the repository at this point in the history
Allows users to manage cacheing behavior.
  • Loading branch information
fb55 committed Oct 2, 2020
1 parent 0c0a8ff commit 6db3de6
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 3 deletions.
5 changes: 4 additions & 1 deletion src/general.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ export function compileGeneralSelector<Node, ElementNode extends Node>(

// Traversal
case "descendant":
if (typeof WeakSet === "undefined") {
if (
options.cacheResults === false ||
typeof WeakSet === "undefined"
) {
return function descendant(elem: ElementNode): boolean {
let current: ElementNode | null = elem;

Expand Down
12 changes: 10 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,13 +111,21 @@ export interface Options<Node, ElementNode extends Node> {
rootFunc?: (element: ElementNode) => boolean;
/**
* The adapter to use when interacting with the backing DOM structure. By
* default it uses domutils.
* default it uses the `domutils` module.
*/
adapter?: Adapter<Node, ElementNode>;
/**
* The context of the current query. Used to
* The context of the current query. Used to limit the scope of searches.
* Can be matched directly using the `:scope` pseudo-selector.
*/
context?: ElementNode | ElementNode[];
/**
* Allow css-select to cache results for some selectors, sometimes greatly
* improving querying performance. Disable this if your document can
* change in between queries with the same compiled selector.
* Defaults to `true`.
*/
cacheResults?: boolean;
}

// Internally, we want to ensure that no propterties are accessed on the passed objects
Expand Down
24 changes: 24 additions & 0 deletions test/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,5 +173,29 @@ describe("API", () => {
CSSselect.selectAll("p", div, { context: div })
).toStrictEqual(p);
});

it("should cache results by default", () => {
const [dom] = parseDOM(
'<div id="foo"><p>bar</p></div>'
) as Element[];
const query = CSSselect.compile("#bar p");

expect(CSSselect.selectAll(query, [dom])).toHaveLength(0);
dom.attribs.id = "bar";
// The query should be cached and the changed attribute should be ignored.
expect(CSSselect.selectAll(query, [dom])).toHaveLength(0);
});

it("should skip cacheing results if asked to", () => {
const [dom] = parseDOM(
'<div id="foo"><p>bar</p></div>'
) as Element[];
const query = CSSselect.compile("#bar p", { cacheResults: false });

expect(CSSselect.selectAll(query, [dom])).toHaveLength(0);
dom.attribs.id = "bar";
// The query should not be cached, the changed attribute should be picked up.
expect(CSSselect.selectAll(query, [dom])).toHaveLength(1);
});
});
});

0 comments on commit 6db3de6

Please sign in to comment.