wrapRegExp.js 2.0 KB

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