index.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var parse = require('ret');
  2. var types = parse.types;
  3. module.exports = function (re, opts) {
  4. if (!opts) opts = {};
  5. var replimit = opts.limit === undefined ? 25 : opts.limit;
  6. if (isRegExp(re)) re = re.source;
  7. else if (typeof re !== 'string') re = String(re);
  8. try { re = parse(re) }
  9. catch (err) { return false }
  10. var reps = 0;
  11. return (function walk (node, starHeight) {
  12. if (node.type === types.REPETITION) {
  13. starHeight ++;
  14. reps ++;
  15. if (starHeight > 1) return false;
  16. if (reps > replimit) return false;
  17. }
  18. if (node.options) {
  19. for (var i = 0, len = node.options.length; i < len; i++) {
  20. var ok = walk({ stack: node.options[i] }, starHeight);
  21. if (!ok) return false;
  22. }
  23. }
  24. var stack = node.stack || (node.value && node.value.stack);
  25. if (!stack) return true;
  26. for (var i = 0; i < stack.length; i++) {
  27. var ok = walk(stack[i], starHeight);
  28. if (!ok) return false;
  29. }
  30. return true;
  31. })(re, 0);
  32. };
  33. function isRegExp (x) {
  34. return {}.toString.call(x) === '[object RegExp]';
  35. }