Untitled

mail@pastecode.io avatar
unknown
typescript
2 months ago
1.1 kB
2
Indexable
Never
class Vector {
    x = 0;
    y = 0;

    constructor(x?: number, y?: number) {
        this.x = x || 0;
        this.y = y || 0;
    }

    magnitude() {
        return Math.sqrt(this.x**2 + this.y**2);
    }

    unit() {
        const m = this.magnitude();
        return new Vector(this.x / m, this.y / m);
    }

    plus(other: Vector) {
        return new Vector(
            this.x + other.x,
            this.y + other.y
        )
    }

    plusEq(other: Vector) {
        this.x += other.x;
        this.y += other.y;
    }

    minus(other: Vector) {
        return new Vector(
            this.x - other.x,
            this.y - other.y
        )
    }

    minusEq(other: Vector) {
        this.x -= other.x;
        this.y -= other.y;
    }

    mul(val: number) {
        return new Vector(
            this.x * val,
            this.y * val
        )
    }

    mulEq(val: number) {
        this.x *= val;
        this.y *= val;
    }

    dot(other: Vector) {
       return this.x * other.x + this.y * other.y; 
    }
}
Leave a Comment