parse.js 839 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. module.exports = parse;
  2. //following http://www.w3.org/TR/css3-selectors/#nth-child-pseudo
  3. //[ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]?
  4. var re_nthElement = /^([+\-]?\d*n)?\s*(?:([+\-]?)\s*(\d+))?$/;
  5. /*
  6. parses a nth-check formula, returns an array of two numbers
  7. */
  8. function parse(formula){
  9. formula = formula.trim().toLowerCase();
  10. if(formula === "even"){
  11. return [2, 0];
  12. } else if(formula === "odd"){
  13. return [2, 1];
  14. } else {
  15. var parsed = formula.match(re_nthElement);
  16. if(!parsed){
  17. throw new SyntaxError("n-th rule couldn't be parsed ('" + formula + "')");
  18. }
  19. var a;
  20. if(parsed[1]){
  21. a = parseInt(parsed[1], 10);
  22. if(isNaN(a)){
  23. if(parsed[1].charAt(0) === "-") a = -1;
  24. else a = 1;
  25. }
  26. } else a = 0;
  27. return [
  28. a,
  29. parsed[3] ? parseInt((parsed[2] || "") + parsed[3], 10) : 0
  30. ];
  31. }
  32. }