UNPKG

vecti

Version:

A tiny TypeScript library for 2D vector math.

112 lines (111 loc) 3.12 kB
class s { /** * Create a vector with the given components. * @param x - The component of the x-axis. * @param y - The component of the y-axis. * @returns The vector. */ constructor(t, i) { this.x = t, this.y = i; } /** * Create a vector with the given components. * @param x - The component of the x-axis. * @param y - The component of the y-axis. * @returns The vector. */ static of([t, i]) { return new s(t, i); } /** * Add another vector to the vector. * @param val - The vector to be added. * @returns The resulting vector of the addition. */ add(t) { return new s(this.x + t.x, this.y + t.y); } /** * Subtract another vector from the vector. * @param val - The vector to be added. * @returns The resulting vector of the subtraction. */ subtract(t) { return new s(this.x - t.x, this.y - t.y); } /** * Multiply the vector by a scalar. * @param scalar - The scalar the vector will be multiplied by. * @returns The resulting vector of the multiplication. */ multiply(t) { return new s(this.x * t, this.y * t); } /** * Divide the vector by a scalar. * @param scalar - The scalar the vector will be divided by. * @returns The resulting vector of the division. */ divide(t) { return new s(this.x / t, this.y / t); } /** * Calculate the dot product of the vector and another vector. * @param other - The other vector used for calculating the dot product. * @returns The dot product. */ dot(t) { return this.x * t.x + this.y * t.y; } /** * Calculate the cross product of the vector and another vector. The cross product of two vectors `a` and `b` is defined as `a.x * b.y - a.y * b.x`. * @param other - The other vector used for calculating the cross product. * @returns The cross product. */ cross(t) { return this.x * t.y - t.x * this.y; } /** * Calculate the Hadamard product of the vector and another vector. * @param other - The other vector used for calculating the Hadamard product. * @returns The Hadamard product. */ hadamard(t) { return new s(this.x * t.x, this.y * t.y); } /** * Calculate the length of the vector using the L2 norm. * @returns The length. */ length() { return Math.sqrt(this.x ** 2 + this.y ** 2); } /** * Normalize the vector using the L2 norm. * @returns The normalized vector. */ normalize() { const t = this.length(); return new s(this.x / t, this.y / t); } /** * Rotate the vector by the given radians counterclockwise. * @param radians - The radians the vector will be rotated by. * @returns The rotated vector. */ rotateByRadians(t) { const i = Math.cos(t), h = Math.sin(t); return new s(this.x * i - this.y * h, this.x * h + this.y * i); } /** * Rotate the vector by the given degrees counterclockwise. * @param degrees - The degrees the vector will be rotated by. * @returns The rotated vector. */ rotateByDegrees(t) { return this.rotateByRadians(t * Math.PI / 180); } } export { s as Vector };