0

I'm trying to make a simple Vector class in Javascript, but since it doesn't support overloading, I experimented with the 'or operator' and came up with the following add function. It works with most inputs except for 0 since it's treated as false instead of a number by the 'or operator'. Is there something else similar in Javascript that I can use?

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

    // possible inputs
    // - add(Vector)
    // - add(Number)
    // - add(Number,Number)
    add(parameter1,parameter2)
    {
        this.x += parameter1.x || parameter1;
        this.y += parameter1.y || parameter2 || parameter1;
    }
    ...
}
Procyon
  • 37
  • 1
  • 4
  • Also relevant: [Is there a “null coalescing” operator in JavaScript?](https://stackoverflow.com/q/476436) – VLAZ Jul 29 '20 at 03:50

1 Answers1

0

Yes, there is the novel Nullish coalescing operator which solves this particular issue.

However, it is not supported in all browser versions.

Edit: NodeJs currently does not support nullish coalescing at allenter image description here

If you aren't restrained by any versions and can use it in your project, however, you're good to go.

Andrei
  • 400
  • 2
  • 6