Skip to content

Instantly share code, notes, and snippets.

@SMotaal
Created April 26, 2019 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SMotaal/7bcb750c9d9b64e839e30d6ab1d2d24e to your computer and use it in GitHub Desktop.
Save SMotaal/7bcb750c9d9b64e839e30d6ab1d2d24e to your computer and use it in GitHub Desktop.
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,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment