You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

compile.js 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. module.exports = compile;
  2. var BaseFuncs = require("boolbase"),
  3. trueFunc = BaseFuncs.trueFunc,
  4. falseFunc = BaseFuncs.falseFunc;
  5. /*
  6. returns a function that checks if an elements index matches the given rule
  7. highly optimized to return the fastest solution
  8. */
  9. function compile(parsed){
  10. var a = parsed[0],
  11. b = parsed[1] - 1;
  12. //when b <= 0, a*n won't be possible for any matches when a < 0
  13. //besides, the specification says that no element is matched when a and b are 0
  14. if(b < 0 && a <= 0) return falseFunc;
  15. //when a is in the range -1..1, it matches any element (so only b is checked)
  16. if(a ===-1) return function(pos){ return pos <= b; };
  17. if(a === 0) return function(pos){ return pos === b; };
  18. //when b <= 0 and a === 1, they match any element
  19. if(a === 1) return b < 0 ? trueFunc : function(pos){ return pos >= b; };
  20. //when a > 0, modulo can be used to check if there is a match
  21. var bMod = b % a;
  22. if(bMod < 0) bMod += a;
  23. if(a > 1){
  24. return function(pos){
  25. return pos >= b && pos % a === bMod;
  26. };
  27. }
  28. a *= -1; //make `a` positive
  29. return function(pos){
  30. return pos <= b && pos % a === bMod;
  31. };
  32. }