nthCheck() API
Relevant source files
The following files were used as context for generating this wiki page:
The nthCheck() API is the primary entry point for the nth-check module, designed to parse and compile CSS nth-child formulas into highly optimized JavaScript functions. It supports standard CSS3 selector syntax, such as 2n+3, even, and odd, allowing developers to verify if a specific element index matches a rule or to generate a sequence of matching indices.
The module focuses on performance by providing specialized logic paths for different types of formulas (e.g., constant offsets, linear increments). While the CSS specification starts counting at 1, the functions generated by this API use 0-based indexing for compatibility with standard JavaScript arrays.
Sources: README.md:5-15, src/index.ts:7-14
Core Functionality and Data Flow
The API operates through a two-stage process: parsing the string formula into a numeric tuple and compiling that tuple into an optimized matcher or generator.
Data Transformation Pipeline
The following diagram illustrates the transition from a string formula to a functional matcher:
The flow shows how nthCheck combines parse and compile, while sequence combines parse and generate.
Sources: src/index.ts:25-50, src/compile.ts:22-114
API Reference
Primary Export: nthCheck(formula)
The default export parses a formula and returns a function that checks an index.
| Feature | Description |
|---|---|
| Input | A string formula (e.g., "2n+1", "even"). |
| Output | A function (index: number) => boolean. |
| Parsing | Converts syntax like even to [2, 0] and odd to [2, 1]. |
| Optimization | Returns boolbase.falseFunc or boolbase.trueFunc for static matches. |
Sources: src/index.ts:25-27, src/parse.ts:20-28, src/compile.ts:40-50
Parser: parse(formula)
The parser breaks down the CSS formula into two components: the step size (a) and the offset (b).
- Logic: It handles signs (
+,-), whitespace, and thenkeyword. - Validation: Throws an
Errorif the formula does not adhere to the expected[+-]? [INTEGER]? {N} [ [+-] [INTEGER] ]?structure.
Sources: src/parse.ts:16-55
Compiler: compile([a, b])
The compiler takes the tuple produced by the parser and returns a predicate function. It includes several optimization branches:
- Static False: If the rule can never match (e.g.,
a <= 0and offsetb < 0). - Linear Range: If
ais-1,0, or1, simple comparisons (<=,===,>=) are used. - Modulo Operation: For
abs(a) > 1, it uses modulo arithmetic to check if(index % absA)matches the calculatedbModulo.
Sources: src/compile.ts:34-62
Sequence Generator: sequence(formula)
Returns a function that, when called repeatedly, produces a monotonously increasing sequence of indices.
The sequence generator maintains internal state n to calculate the next index in the series.
Sources: src/index.ts:51-53, src/compile.ts:98-114
Implementation Details
Optimized Matcher Logic
The compile function adjusts the offset b by subtracting 1 to align CSS 1-based indexing with JavaScript 0-based indexing.
export function compile(parsed: [a: number, b: number]): (index: number) => boolean {
const a = parsed[0];
const b = parsed[1] - 1; // Convert to zero-indexed
if (b < 0 && a <= 0) return boolbase.falseFunc;
if (a === 0) return (index) => index === b;
// ... specialized branches
}
Sources: src/compile.ts:37-46
Supported Formulas
Common valid and invalid patterns found in the project test suites and fixtures:
| Formula | Parsed [a, b] | Description |
|---|---|---|
even | [2, 0] | Every second element starting from 0 (index-wise). |
odd | [2, 1] | Every second element starting from 1 (index-wise). |
3n+2 | [3, 2] | Matches indices 1, 4, 7, etc. |
-n+3 | [-1, 3] | Matches indices <= 2. |
asdf | Throws Error | Invalid non-numeric input. |
Sources: src/fixtures/rules.ts:1-45, src/parse.ts:20-28
Summary
The nthCheck() API provides a robust and performant way to handle CSS-like index selection logic in JavaScript. By separating the concerns of parsing, validation, and execution, it allows for both high-speed element filtering via compile and efficient sequence iteration via generate. Its adherence to the CSS3 Selectors specification ensures compatibility with standard web styling rules.
Sources: README.md:1-15, src/index.ts:1-25