RegExp.escape()

C. Scott Ananian ecmascript at cscott.net
Sat Jun 13 20:18:06 UTC 2015


To throw some more paint on the bikeshed:

The "instanceof RegExp" and "RegExp(...)" parts of the "perfect"
implementation of `RegExp.tag` should also be fixed to play nicely with
species.

I think Allen and I would say that you should *not* use the species pattern
for instantiating the new regexp (because this is a factory), but you
should be doing `new this(...)` to create the result, instead of
`RegExp(...)`.  (Domenic might disagree, but this is the pattern the ES6
spec is currently consistent with.)

The `instanceof RegExp` test might also be reviewed.  It might be okay, but
perhaps you want to invoke a `toRegExp` method instead, or just look at
`source`, so that we used duck typing instead of a fixed inheritance
chain.  You could even define `String#toRegExp` and have that handle proper
escaping.  This pattern might not play as nicely with subtyping, though, so
perhaps using `this.escape(string)` (returning an instance of `this`) is in
fact preferable.  Everything other than a string might be passed through
`new this(somethingelse).source` which could cast it from a "base RegExp"
to a subclass as necessary. You could handle whatever conversions are
necessary in the constructor for your subclass.

If we did want to use the species pattern, the best way (IMO) would be to
expose the fundamental alternation/concatenation/etc operators.  For
example, `RegExp.prototype.concat(x)` would use the species pattern to
produce a result, and would also handle escaping `x` if it was a string.
The set of instance methods needed is large but not *too* large: `concat`,
`alt`, `mult`, and `group` (with options) might be sufficient.
  --scott
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150613/de30cb66/attachment.html>


More information about the es-discuss mailing list