Skip to content

Instantly share code, notes, and snippets.

@nickcarenza
Created August 8, 2016 17:34
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 nickcarenza/ff880d3fd91fbb519d0321f21d3672ce to your computer and use it in GitHub Desktop.
Save nickcarenza/ff880d3fd91fbb519d0321f21d3672ce to your computer and use it in GitHub Desktop.
Implements named parameters on javascript regexp with use of getters.
/**
* The idea here is to support named regexp parameters by returning a proxy with a getter function
* TODO add Proxy
*/
class RegExp2 extends RegExp {
constructor(regexpStr, ...names) {
super(regexpStr)
this.names = names;
}
exec(str) {
return new RegExp2Result(this, super.exec(str));
}
}
class RegExp2Result {
constructor(regexp2, matches) {
this.regexp2 = regexp2;
this.matches = matches;
/*return new Proxy(this, {
get: (target, name) => {
if (matches === null) {
return null;
}
let index = target.names.indexOf(name);
if (index === -1) {
return false;
}
// The first element in the matches array is the full string
return this.matches[index + 1];
}
});*/
for (var i in regexp2.names) {
var name = regexp2.names[i];
Object.defineProperty(this, name, { get: function () {
if (matches === null) {
return null;
}
let index = regexp2.names.indexOf(name);
if (index === -1) {
return false;
}
// The first element in the matches array is the full string
return matches[index + 1];
} });
}
}
}
var chai = require('chai')
, expect = chai.expect
, should = chai.should();
var re2 = new RegExp2('hello (\\w+)', ['name']);
var re2resmatch = re2.exec('hello john');
re2resmatch.name.should.equal('john');
expect(re2resmatch.name2).to.be.undefined;
var re2resnomatch = re2.exec('hello');
expect(re2resnomatch.name).to.be.null;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment