wrapRegExp.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import _typeof from "./typeof.js";
  2. import setPrototypeOf from "./setPrototypeOf.js";
  3. import inherits from "./inherits.js";
  4. function _wrapRegExp() {
  5. _wrapRegExp = function _wrapRegExp(e, r) {
  6. return new BabelRegExp(e, void 0, r);
  7. };
  8. var e = RegExp.prototype,
  9. r = new WeakMap();
  10. function BabelRegExp(e, t, p) {
  11. var o = RegExp(e, t);
  12. return r.set(o, p || r.get(e)), setPrototypeOf(o, BabelRegExp.prototype);
  13. }
  14. function buildGroups(e, t) {
  15. var p = r.get(t);
  16. return Object.keys(p).reduce(function (r, t) {
  17. var o = p[t];
  18. if ("number" == typeof o) r[t] = e[o];else {
  19. for (var i = 0; void 0 === e[o[i]] && i + 1 < o.length;) i++;
  20. r[t] = e[o[i]];
  21. }
  22. return r;
  23. }, Object.create(null));
  24. }
  25. return inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (r) {
  26. var t = e.exec.call(this, r);
  27. if (t) {
  28. t.groups = buildGroups(t, this);
  29. var p = t.indices;
  30. p && (p.groups = buildGroups(p, this));
  31. }
  32. return t;
  33. }, BabelRegExp.prototype[Symbol.replace] = function (t, p) {
  34. if ("string" == typeof p) {
  35. var o = r.get(this);
  36. return e[Symbol.replace].call(this, t, p.replace(/\$<([^>]+)>/g, function (e, r) {
  37. var t = o[r];
  38. return "$" + (Array.isArray(t) ? t.join("$") : t);
  39. }));
  40. }
  41. if ("function" == typeof p) {
  42. var i = this;
  43. return e[Symbol.replace].call(this, t, function () {
  44. var e = arguments;
  45. return "object" != _typeof(e[e.length - 1]) && (e = [].slice.call(e)).push(buildGroups(e, i)), p.apply(this, e);
  46. });
  47. }
  48. return e[Symbol.replace].call(this, t, p);
  49. }, _wrapRegExp.apply(this, arguments);
  50. }
  51. export { _wrapRegExp as default };