Skip to content
This repository was archived by the owner on Apr 3, 2025. It is now read-only.
This repository was archived by the owner on Apr 3, 2025. It is now read-only.

[IDEA] operator overloading via Proxy traps #54

Open
@Haringat

Description

@Haringat

There is already the possibility to trap certain operators on objects and similar (e.g. () or new) by using Proxy traps. For consistency it would seem sensible to put the overloading of other operators there as well.
It could work like this:

class Vector {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}

Vector.prototype = new Proxy(Vector.prototype, {
    add(target, other) {
        if (typeof other === "number") {
            return new Vector(
                target.x + other,
                target.y + other
            );
        } else if (typeof other === "object" && typeof other.x === "number" && typeof other.y === "number") { // TODO: add case for bigint?
            return new Vector(
                target.x + other.x,
                target.y + other.y
            );
        } else {
            throw new Error("unsupported operand provided for addition of vector");
        }
    }
    // TODO: add further operators
});

const one = new Vector(1, 1);
const two = one + one;
console.log(two); // Vector { x: 2, y: 2 }
const three = one + 2;
console.log(three); // Vector { x: 3, y: 3 }
const bad = 3 + one; // coercion appearing as number has no overload (and cannot have one) for objects
console.log(bad); // 3[object Object]

The "sugared" version is to be defined.

This would of course bring some further changes to the proposal, most notably that the overloaded operators would be inherited and always be present as there is no "with" to explicitly enable them. However, that would probably not be a problem as it is in line with how Proxies (and thus our currently limited operator overloading) works.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions