Proxy: more handlers for operators


The current Proxy handler APIs covered some of useful functions with a small set of operators, and I'm working on that a library makes a better representation for matrix computing just like the Python does:

m0 = numpy.asmatrix(...)
m1 = 20 * m0 + 10

The last expr represents a computation on the elements of the matrix m0, Python language uses some magic methods like __add__() for custom the add operator impl on the matrix objects. So the additions of these handlers handlers.addOperator, handlers.mulOperator would make this possible to be working on JavaScript instead of:

const m0 = numpy.asmatrix(...);
const m1 = m0.mul(20).add(10);

This would constitute operator overloading, which is being proposed already:

I believe your semantics, however, would cause a performance hit on every operator usage in the language, which is why I believe implementers have been reluctant to support such a proposal in the past.

1 Like

Thanks, @ljharb.

I believe your semantics, however, would cause a performance hit on every operator usage in the language

The performance hit that you mentioned should be occurred on other trap functions at Proxy, and I don't think the hit should have hit on "every" object, it's just on Proxy-ed object.

As for the operator overloading proposal, I'm confused. Because these traps like deleteProperty, apply and construct should also be done with operator overloading, what's the differences in the future language? There are too much ways to do the same thing.

I assume (I’m not a browser implementer and i don’t have expertise on performance here) that those operations aren’t often done in hot code paths, whereas the logical and comparison and math and equality operators are.

1 Like

That's a good point about Proxy already overloading operators. For this reason, it seems like a fit place for adding more. But I'd be interested if the overload proposal provides a more performant way.

There's also the confounding issue of things like:

  • Existing asm.js code using +x to coerce to double and x | 0/~~x to coerce to a 32-bit signed integer (web compat issue)
  • People using !!x to coerce to a boolean and expecting -x to coerce to a number
  • {} == "[object Object]" and "[object Object]" == {} both evaluate to true, so simple proxy dispatch can't encompass that.
  • It would be very useful to allow both vec3 + 2 and 2 + vec3, and you can't do that with single method dispatch. (This is part of what makes Julia so attractive for analysis, and you can get to stuff that looks almost like it should require static analysis.)