Performance Optimizations
Relevant source files
The following files were used as context for generating this wiki page:
The nth-check module is designed to parse and compile CSS nth-child formulas into highly optimized JavaScript functions. By pre-compiling complex formulas like 2n+3 or -n+5 into specialized closures, the module avoids the overhead of repeated string parsing or complex loop iterations during element matching in DOM-like structures.
The core philosophy focuses on identifying specific mathematical properties of the an+b formula to return the most efficient boolean check possible. This approach ensures high-speed execution for common selectors while strictly adhering to the W3C CSS Selectors specification.
Sources: README.md:1-12, package.json:5-7
Compilation Strategies
The compile function analyzes the [a, b] tuple to determine the most efficient functional path. It converts the 1-based index used in CSS to a 0-based index used internally by subtracting 1 from the offset b.
Sources: src/compile.ts:25-28
Optimized Functional Paths
The compiler selects a specialized function based on the value of the step size a:
| Condition | Optimization Strategy | Implementation Detail |
|---|---|---|
a <= 0 and b < 0 | Empty Set | Returns boolbase.falseFunc. |
a === -1 | Upper Bound | Returns index <= b. |
a === 0 | Exact Match | Returns index === b. |
a === 1 and b < 0 | Universal Match | Returns boolbase.trueFunc. |
a === 1 and b >= 0 | Lower Bound | Returns index >= b. |
a > 1 | Modulo Check (Positive) | Checks if index >= b and matches modulo. |
a < -1 | Modulo Check (Negative) | Checks if index <= b and matches modulo. |
Sources: src/compile.ts:38-60
Logic Flow for Compiler Optimization
The following diagram illustrates the decision-making process within the compile function to return the optimal matching closure.
The diagram shows how nth-check branches into specific optimizations to avoid general-purpose math when simpler comparisons suffice.
Sources: src/compile.ts:24-60
Parsing and Static Analysis
The parsing phase in src/parse.ts contributes to performance by performing a single pass over the formula string and handling common keywords as constants.
- Keyword Mapping: Formulas like "even" and "odd" are immediately mapped to
[2, 0]and[2, 1]respectively, bypassing the complex regex-like parsing logic. - Integer Parsing: Uses character code comparisons (
ZEROtoNINE) rather thanparseInt()orRegular Expressionsfor higher performance during number extraction. - Sign Handling: Uses a dedicated
readSignhelper to manage+and-prefixes efficiently.
Sources: src/parse.ts:16-25, src/parse.ts:80-94
Generator Optimizations
The generate function provides a performance-oriented way to produce increasing sequences of indices. Instead of calculating every possible index and filtering, it uses the formula logic to jump directly to valid values.
- Negative Step Handling: For negative
a, the generator calculates the minimum valid value and uses a positive stepaPosto ensure the sequence is monotonically increasing until it hits the boundb. - Initial Offset Adjustment: If
b < 0for a positivea, the generator calculates the first non-negative starting point usingMath.ceil(-b / a)to avoid unnecessary iterations or negative indices.
Sources: src/compile.ts:98-124
Project Tooling for Performance
The project maintains performance through strict linting and build configurations:
- Biome Linter: Configured to enforce
useTopLevelRegexandnoConstantBinaryExpressionsto prevent runtime overhead in hot code paths. - Side Effects: The
package.jsonmarks the module assideEffects: false, enabling better tree-shaking in modern bundlers. - Dependency Minimization: Relies only on
boolbaseto keep the execution stack shallow.
Sources: biome.json:34, package.json:9, package.json:71
Summary
nth-check achieves high performance by transforming CSS selectors into specialized JavaScript closures. By categorizing formulas into specific mathematical cases (exact match, range bounds, or modulo arithmetic), it ensures that the resulting matching functions perform the minimum number of operations required per index check.
Sources: src/compile.ts:6-60, README.md:7-12