wrapRegExp.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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, t) {
  37. if ("" === t) return e;
  38. var p = o[r];
  39. return Array.isArray(p) ? "$" + p.join("$") : "number" == typeof p ? "$" + p : "";
  40. }));
  41. }
  42. if ("function" == typeof p) {
  43. var i = this;
  44. return e[Symbol.replace].call(this, t, function () {
  45. var e = arguments;
  46. return "object" != _typeof(e[e.length - 1]) && (e = [].slice.call(e)).push(buildGroups(e, i)), p.apply(this, e);
  47. });
  48. }
  49. return e[Symbol.replace].call(this, t, p);
  50. }, _wrapRegExp.apply(this, arguments);
  51. }
  52. export { _wrapRegExp as default };