Skip to content

Instantly share code, notes, and snippets.

@TooTallNate
Created November 16, 2015 21:03
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 TooTallNate/34a2e8124571c93422ff to your computer and use it in GitHub Desktop.
Save TooTallNate/34a2e8124571c93422ff to your computer and use it in GitHub Desktop.
for (let match of /foo/g.exec('foo bar baz')) console.log(match);
require('./MatchIterator');
// if we want to be bad…
String.prototype.match = (function (match) {
return function (regexp) {
var m = match.apply(this, arguments);
if (m) m[Symbol.iterator] = () => MatchIterator(this, regexp, regexp.global ? null : m);
return m;
};
})(String.prototype.match);
RegExp.prototype.exec = (function (exec) {
return function (str) {
var m = exec.apply(this, arguments);
if (m) m[Symbol.iterator] = () => MatchIterator(str, this, m);
return m;
};
})(RegExp.prototype.exec);
function *MatchIterator (string, regexp, match) {
if (match) yield match;
match = regexp.exec(string);
while (match != null) {
yield match;
match = regexp.exec(string);
}
};
module.exports = MatchIterator;
require('./extend');
var iterator;
iterator = 'foo bar baz'.match(/\bba\w\b/g);
console.log('match iterator', iterator);
// match iterator [ 'bar', 'baz' ]
console.log([...iterator]);
// [ [ 'bar', index: 4, input: 'foo bar baz' ],
// [ 'baz', index: 8, input: 'foo bar baz' ] ]
iterator = /\bba\w\b/g.exec('foo bar baz');
console.log('exec iterator', iterator);
// exec iterator [ 'bar', index: 4, input: 'foo bar baz' ]
console.log([...iterator]);
// [ [ 'bar', index: 4, input: 'foo bar baz' ],
// [ 'baz', index: 8, input: 'foo bar baz' ] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment