parse.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. "use strict";
  2. // Following http://www.w3.org/TR/css3-selectors/#nth-child-pseudo
  3. Object.defineProperty(exports, "__esModule", { value: true });
  4. exports.parse = void 0;
  5. // [ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]?
  6. var 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. */
  14. function 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. }
  39. exports.parse = parse;