Published
Edited
Oct 6, 2020
Importers
Insert cell
md`# Vector2D`
Insert cell
class Vector2D extends Array {
constructor(x = 1, y = 0) {
super(x, y);
}

set x(v) {
this[0] = v;
}

set y(v) {
this[1] = v;
}

get x() {
return this[0];
}

get y() {
return this[1];
}

get length() {
return Math.hypot(this.x, this.y);
}

get dir() {
return Math.atan2(this.y, this.x);
}

copy() {
return new Vector2D(this.x, this.y);
}

add(v) {
this.x += v.x;
this.y += v.y;
return this;
}

sub(v) {
this.x -= v.x;
this.y -= v.y;
return this;
}

scale(a) {
this.x *= a;
this.y *= a;
return this;
}

cross(v) {
return this.x * v.y - v.x * this.y;
}

dot(v) {
return this.x * v.x + v.y * this.y;
}

normalize() {
return this.scale(1 / this.length);
}

rotate(rad) {
const c = Math.cos(rad),
s = Math.sin(rad);
const [x, y] = this;

this.x = x * c + y * -s;
this.y = x * s + y * c;

return this;
}
}
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more