smotaal
4/26/2019 - 11:51 PM

ES2019: Optimized `matchAll` implementation

ES2019: Optimized matchAll implementation

export default Function.call.bind(
  // /* TODO: Uncomment eventually  */ String.prototype.matchAll ||
  {
    /**
     * @this {string}
     * @param {RegExp | string} pattern
     */
    *matchAll() {
      const matcher = arguments[0] && (arguments[0] instanceof RegExp ? arguments[0] : RegExp(arguments[0], 'g'));
      const string = String(this);
      for (
        let match, lastIndex = ((matcher.lastIndex = null), -1);
        lastIndex <
        ((match = matcher.exec(string)) ? (lastIndex = matcher.lastIndex + (match[0].length === 0)) : lastIndex);
        yield match, matcher.lastIndex = lastIndex
      );
    },
  }.matchAll,
)