test.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. var nthCheck = require("./"),
  2. assert = require("assert");
  3. var invalid = ["-", "asdf", "2n+-0", "2+0", "- 1n", "-1 n"];
  4. function parseInvalid(){
  5. invalid.forEach(function(formula){
  6. assert.throws(function(){
  7. nthCheck.parse(formula);
  8. },
  9. SyntaxError,
  10. formula
  11. );
  12. });
  13. }
  14. var valid = {
  15. "1": [ 0, 1 ],
  16. "2": [ 0, 2 ],
  17. "3": [ 0, 3 ],
  18. "5": [ 0, 5 ],
  19. " 1 ": [ 0, 1 ],
  20. " 5 ": [ 0, 5 ],
  21. "+2n + 1": [ 2, 1 ],
  22. "-1": [ 0, -1 ],
  23. "-1n + 3": [ -1, 3 ],
  24. "-1n+3": [ -1, 3 ],
  25. "-n+2": [ -1, 2 ],
  26. "-n+3": [ -1, 3 ],
  27. "0n+3": [ 0, 3 ],
  28. "1n": [ 1, 0 ],
  29. "1n+0": [ 1, 0 ],
  30. "2n": [ 2, 0 ],
  31. "2n + 1": [ 2, 1 ],
  32. "2n+1": [ 2, 1 ],
  33. "3n": [ 3, 0 ],
  34. "3n+0": [ 3, 0 ],
  35. "3n+1": [ 3, 1 ],
  36. "3n+2": [ 3, 2 ],
  37. "3n+3": [ 3, 3 ],
  38. "3n-1": [ 3, -1 ],
  39. "3n-2": [ 3, -2 ],
  40. "3n-3": [ 3, -3 ],
  41. even: [ 2, 0 ],
  42. n: [ 1, 0 ],
  43. "n+2": [ 1, 2 ],
  44. odd: [ 2, 1 ],
  45. //surprisingly, neither sizzle, qwery or nwmatcher cover these cases
  46. "-4n+13": [-4, 13],
  47. "-2n + 12": [-2, 12]
  48. };
  49. function parseValid(){
  50. Object.keys(valid).forEach(function(formula){
  51. assert.deepEqual(nthCheck.parse(formula), valid[formula], formula);
  52. });
  53. }
  54. function testValid(){
  55. Object.keys(valid).forEach(function(formula){
  56. testFormula(valid[formula], formula);
  57. });
  58. }
  59. var valArray = Array.apply(null, Array(2e3)).map(function(_, i){return i;});
  60. function testFormula(formula, name){
  61. var filtered = valArray.filter(nthCheck.compile(formula)),
  62. iterated = stupidNth(formula);
  63. try {
  64. assert.deepEqual(filtered, iterated, name);
  65. } catch(e){
  66. e.expected = JSON.stringify(iterated) + " " + name;
  67. e.actual = JSON.stringify(filtered) + " " + name;
  68. throw e;
  69. }
  70. }
  71. function stupidNth(formula, limit){
  72. var a = formula[0],
  73. b = formula[1];
  74. if(a === 0 && b > 0) return [b - 1];
  75. //taken from qwery
  76. return valArray.filter(function(val){
  77. for(var i = b, l = valArray.length; ((a > 0) ? (i <= l) : (i >= 1)); i += a){
  78. if(val === valArray[i - 1]) return true;
  79. }
  80. });
  81. }
  82. process.stdout.write("- parser");
  83. process.stdout.write("\n - parse invalid:\t");
  84. parseInvalid();
  85. process.stdout.write("X\n - parse valid:\t");
  86. parseValid();
  87. process.stdout.write("X\n- check values: \t");
  88. testValid();
  89. process.stdout.write("X\n");