This example: when /^foo/ ~> ... // matches ifinputis a string that starts with 'foo'
suggests that if i wanted to match when input was a regular expression with matching source/flags/lastIndex, i'd need to do something like when x if (matchesRegex(input, /^foo/)) ~> or similar.
Is this the only way to achieve the matching I'm interested in?
Separately, what would when RegExp('^foo') ~> match on?
Since RegExp instances are objects, you can just destructure on objects:
match (/^foo/ig) {
when {global: true, lastIndex} ~>
console.log('got a global regex currently at', lastIndex)
}
This ofc already works with existing pattern matching:
➜ node
> const {flags, global, source, unicode} = /^foo/ig
undefined
> {flags, global, source, unicode}
{ flags: 'gi', global: true, source: '^foo', unicode: false }
>
And of course, you can similarly match against match objects if you want something better than a boolean check:
match (str.match(/^foo/)) {
...array or object cases...
}
That all makes sense; I'm now mainly wondering if the confusion of the regex literal syntax meaning something different inside when than outside is worth the convenience for the "matching string input against a regex" case.
tbh, literal regexes aren't supported at all by the current destructuring syntax, which I think is a pretty good argument for dropping them from this version of the proposal.
They would still be supported eventually by collection literals, since you could then do:
when /(?<year>\d{4})-(?<month>\d{2})/u#{groups: {year, month}} ~> {
console.log(`The year is ${year}, and the month is ${month}`)
},
(this is from one of the current examples in the tagged literals proposal!)
And it's easy enough to use guards to support this use-case in the meantime. Not having access to the match makes it relatively low-value anyway. I'm fine dropping it altogether for now?
If it was dropped as a special case, I'd assume it'd use Object.is like the other forms?
If it was dropped as a special case, it would become invalid syntax altogether. You would NOT be able to do anything that looks like when /foo/ ~>, because RegExpLiteral would no longer be in the grammar for it.
Using Object.is for literal RegExps would be so strange and so far from what I'd expect that to do? And definitely a hazard if we introduce the collection literals and folks forget the #{...} bit.
Got it.
I think dropping that syntax for now might be best, especially since there'd be room to add it later.
I agree, tbh. Specially with the current pattern I'm on of reducing-and-polishing. Thanks for bringing this up!
removed in a6c3afc. All done!