wrapRegExp.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. var _typeof = require("./typeof.js")["default"];
  2. var _WeakMap = require("@babel/runtime-corejs2/core-js/weak-map");
  3. var _Object$keys = require("@babel/runtime-corejs2/core-js/object/keys");
  4. var _Object$create = require("@babel/runtime-corejs2/core-js/object/create");
  5. var _Symbol$replace = require("@babel/runtime-corejs2/core-js/symbol/replace");
  6. var setPrototypeOf = require("./setPrototypeOf.js");
  7. var inherits = require("./inherits.js");
  8. function _wrapRegExp() {
  9. module.exports = _wrapRegExp = function _wrapRegExp(re, groups) {
  10. return new BabelRegExp(re, void 0, groups);
  11. }, module.exports.__esModule = true, module.exports["default"] = module.exports;
  12. var _super = RegExp.prototype,
  13. _groups = new _WeakMap();
  14. function BabelRegExp(re, flags, groups) {
  15. var _this = new RegExp(re, flags);
  16. return _groups.set(_this, groups || _groups.get(re)), setPrototypeOf(_this, BabelRegExp.prototype);
  17. }
  18. function buildGroups(result, re) {
  19. var g = _groups.get(re);
  20. return _Object$keys(g).reduce(function (groups, name) {
  21. return groups[name] = result[g[name]], groups;
  22. }, _Object$create(null));
  23. }
  24. return inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (str) {
  25. var result = _super.exec.call(this, str);
  26. return result && (result.groups = buildGroups(result, this)), result;
  27. }, BabelRegExp.prototype[_Symbol$replace] = function (str, substitution) {
  28. if ("string" == typeof substitution) {
  29. var groups = _groups.get(this);
  30. return _super[_Symbol$replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) {
  31. return "$" + groups[name];
  32. }));
  33. }
  34. if ("function" == typeof substitution) {
  35. var _this = this;
  36. return _super[_Symbol$replace].call(this, str, function () {
  37. var args = arguments;
  38. return "object" != _typeof(args[args.length - 1]) && (args = [].slice.call(args)).push(buildGroups(args, _this)), substitution.apply(this, args);
  39. });
  40. }
  41. return _super[_Symbol$replace].call(this, str, substitution);
  42. }, _wrapRegExp.apply(this, arguments);
  43. }
  44. module.exports = _wrapRegExp, module.exports.__esModule = true, module.exports["default"] = module.exports;