blob: f98d920776c4180cd2831683149d927e6a7c9915 [file] [log] [blame]
Tim van der Lippe706ec962021-06-04 13:24:42 +01001"use strict";
2// Following http://www.w3.org/TR/css3-selectors/#nth-child-pseudo
3Object.defineProperty(exports, "__esModule", { value: true });
4exports.parse = void 0;
5// [ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]?
6var RE_NTH_ELEMENT = /^([+-]?\d*n)?\s*(?:([+-]?)\s*(\d+))?$/;
7/**
8 * Parses an expression.
9 *
10 * @throws An `Error` if parsing fails.
11 * @returns An array containing the integer step size and the integer offset of the nth rule.
12 * @example nthCheck.parse("2n+3"); // returns [2, 3]
13 */
14function parse(formula) {
15 formula = formula.trim().toLowerCase();
16 if (formula === "even") {
17 return [2, 0];
18 }
19 else if (formula === "odd") {
20 return [2, 1];
21 }
22 var parsed = formula.match(RE_NTH_ELEMENT);
23 if (!parsed) {
24 throw new Error("n-th rule couldn't be parsed ('" + formula + "')");
25 }
26 var a;
27 if (parsed[1]) {
28 a = parseInt(parsed[1], 10);
29 if (isNaN(a)) {
30 a = parsed[1].startsWith("-") ? -1 : 1;
31 }
32 }
33 else
34 a = 0;
35 var b = (parsed[2] === "-" ? -1 : 1) *
36 (parsed[3] ? parseInt(parsed[3], 10) : 0);
37 return [a, b];
38}
39exports.parse = parse;