wrapRegExp.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. var _Object$create = require("../core-js/object/create");
  2. var _Object$keys = require("../core-js/object/keys");
  3. var _typeof = require("../helpers/typeof");
  4. var _Symbol$replace = require("../core-js/symbol/replace");
  5. var _WeakMap = require("../core-js/weak-map");
  6. var wrapNativeSuper = require("./wrapNativeSuper");
  7. var getPrototypeOf = require("./getPrototypeOf");
  8. var possibleConstructorReturn = require("./possibleConstructorReturn");
  9. var inherits = require("./inherits");
  10. function _wrapRegExp(re, groups) {
  11. module.exports = _wrapRegExp = function _wrapRegExp(re, groups) {
  12. return new BabelRegExp(re, groups);
  13. };
  14. var _RegExp = wrapNativeSuper(RegExp);
  15. var _super = RegExp.prototype;
  16. var _groups = new _WeakMap();
  17. function BabelRegExp(re, groups) {
  18. var _this = _RegExp.call(this, re);
  19. _groups.set(_this, groups);
  20. return _this;
  21. }
  22. inherits(BabelRegExp, _RegExp);
  23. BabelRegExp.prototype.exec = function (str) {
  24. var result = _super.exec.call(this, str);
  25. if (result) result.groups = buildGroups(result, this);
  26. return result;
  27. };
  28. BabelRegExp.prototype[_Symbol$replace] = function (str, substitution) {
  29. if (typeof substitution === "string") {
  30. var groups = _groups.get(this);
  31. return _super[_Symbol$replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) {
  32. return "$" + groups[name];
  33. }));
  34. } else if (typeof substitution === "function") {
  35. var _this = this;
  36. return _super[_Symbol$replace].call(this, str, function () {
  37. var args = [];
  38. args.push.apply(args, arguments);
  39. if (_typeof(args[args.length - 1]) !== "object") {
  40. args.push(buildGroups(args, _this));
  41. }
  42. return substitution.apply(this, args);
  43. });
  44. } else {
  45. return _super[_Symbol$replace].call(this, str, substitution);
  46. }
  47. };
  48. function buildGroups(result, re) {
  49. var g = _groups.get(re);
  50. return _Object$keys(g).reduce(function (groups, name) {
  51. groups[name] = result[g[name]];
  52. return groups;
  53. }, _Object$create(null));
  54. }
  55. return _wrapRegExp.apply(this, arguments);
  56. }
  57. module.exports = _wrapRegExp;