"Approx-equal" operator

Dmitry Soshnikov dmitry.soshnikov at gmail.com
Sun Dec 18 13:52:49 PST 2011


On 18.12.2011 23:18, Mike Samuel wrote:
> 2011/12/17 Dmitry Soshnikov<dmitry.soshnikov at gmail.com>:
>> Hi,
>>
>> Just recently was working with Ruby's code. And found useful again its
>> (actually from Perl) "approximately equal" operator: =~
> Perl's =~ operator is more comparable to String.prototype.match than
> RegExp.prototype.test.
>
> Perl operators can be used in either scalar or list contexts unlike
> ecmascript (see perldoc for wantarray) and it's true that =~ produces
> a boolean when used in a scalar context, but since match returns null
> on zero matches, it can still be used in conditions.  When used in a
> non-scalar context, =~ produces a list of the matches:
>
>      perl -e 'my $s = "foo"; print join ",", ($s =~ /o/g)'
>
> prints
>
>     o,o

Perhaps, I don't know Perl enough. The talk isn't about Perl though. We 
may adjust the semantics for ES as _we_ wish, not Perl.

>
> Even ignoring order of evaluation, desugaring a ~= b to b.test(a)
> would cause the seemingly straightforward
>
>     var myRegex = /foo/g;  // Used for a global replace in other code.
>     if ("foo" ~= myRegex) { alert(1); }
>     if ("foo" ~= myRegex) { alert(2); }
>     if ("foo" ~= myRegex) { alert(3); }
>
> to alert 1 and 3 only.

Because of lastIndex, I understand. Though nobody says we have to 
directly desugar it to .test(...) method. Obviously, it should handle 
the case correctly.

Dmitry.



More information about the es-discuss mailing list