[79a0317] | 1 | // Following http://www.w3.org/TR/css3-selectors/#nth-child-pseudo
|
---|
| 2 | // Whitespace as per https://www.w3.org/TR/selectors-3/#lex is " \t\r\n\f"
|
---|
| 3 | const whitespace = new Set([9, 10, 12, 13, 32]);
|
---|
| 4 | const ZERO = "0".charCodeAt(0);
|
---|
| 5 | const NINE = "9".charCodeAt(0);
|
---|
| 6 | /**
|
---|
| 7 | * Parses an expression.
|
---|
| 8 | *
|
---|
| 9 | * @throws An `Error` if parsing fails.
|
---|
| 10 | * @returns An array containing the integer step size and the integer offset of the nth rule.
|
---|
| 11 | * @example nthCheck.parse("2n+3"); // returns [2, 3]
|
---|
| 12 | */
|
---|
| 13 | export function parse(formula) {
|
---|
| 14 | formula = formula.trim().toLowerCase();
|
---|
| 15 | if (formula === "even") {
|
---|
| 16 | return [2, 0];
|
---|
| 17 | }
|
---|
| 18 | else if (formula === "odd") {
|
---|
| 19 | return [2, 1];
|
---|
| 20 | }
|
---|
| 21 | // Parse [ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]?
|
---|
| 22 | let idx = 0;
|
---|
| 23 | let a = 0;
|
---|
| 24 | let sign = readSign();
|
---|
| 25 | let number = readNumber();
|
---|
| 26 | if (idx < formula.length && formula.charAt(idx) === "n") {
|
---|
| 27 | idx++;
|
---|
| 28 | a = sign * (number !== null && number !== void 0 ? number : 1);
|
---|
| 29 | skipWhitespace();
|
---|
| 30 | if (idx < formula.length) {
|
---|
| 31 | sign = readSign();
|
---|
| 32 | skipWhitespace();
|
---|
| 33 | number = readNumber();
|
---|
| 34 | }
|
---|
| 35 | else {
|
---|
| 36 | sign = number = 0;
|
---|
| 37 | }
|
---|
| 38 | }
|
---|
| 39 | // Throw if there is anything else
|
---|
| 40 | if (number === null || idx < formula.length) {
|
---|
| 41 | throw new Error(`n-th rule couldn't be parsed ('${formula}')`);
|
---|
| 42 | }
|
---|
| 43 | return [a, sign * number];
|
---|
| 44 | function readSign() {
|
---|
| 45 | if (formula.charAt(idx) === "-") {
|
---|
| 46 | idx++;
|
---|
| 47 | return -1;
|
---|
| 48 | }
|
---|
| 49 | if (formula.charAt(idx) === "+") {
|
---|
| 50 | idx++;
|
---|
| 51 | }
|
---|
| 52 | return 1;
|
---|
| 53 | }
|
---|
| 54 | function readNumber() {
|
---|
| 55 | const start = idx;
|
---|
| 56 | let value = 0;
|
---|
| 57 | while (idx < formula.length &&
|
---|
| 58 | formula.charCodeAt(idx) >= ZERO &&
|
---|
| 59 | formula.charCodeAt(idx) <= NINE) {
|
---|
| 60 | value = value * 10 + (formula.charCodeAt(idx) - ZERO);
|
---|
| 61 | idx++;
|
---|
| 62 | }
|
---|
| 63 | // Return `null` if we didn't read anything.
|
---|
| 64 | return idx === start ? null : value;
|
---|
| 65 | }
|
---|
| 66 | function skipWhitespace() {
|
---|
| 67 | while (idx < formula.length &&
|
---|
| 68 | whitespace.has(formula.charCodeAt(idx))) {
|
---|
| 69 | idx++;
|
---|
| 70 | }
|
---|
| 71 | }
|
---|
| 72 | }
|
---|
| 73 | //# sourceMappingURL=parse.js.map |
---|