Skip to content

Instantly share code, notes, and snippets.

@FreekPaans
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FreekPaans/1ec56f58d3cbb2c1d7f1 to your computer and use it in GitHub Desktop.
Save FreekPaans/1ec56f58d3cbb2c1d7f1 to your computer and use it in GitHub Desktop.
function Vector(rep) {
switch (rep) {
case Vector.representations.Polar:
this.vector = { rep: rep, r: arguments[1], a: arguments[2] }
break;
case Vector.representations.Rectangular:
this.vector = { rep: rep, x: arguments[1], y: arguments[2] }
break;
default:
throw Error("Unknown representation " + rep)
}
var assertVector = function (vector) {
if (!(vector instanceof Vector)) {
throw Error("addend not a Vector")
}
}
var assertPolar = function (vector) {
if (!(vector.vector.rep === Vector.representations.Polar)) {
throw Error("vector not in polar representation")
}
}
var polar2Rect = function (vector) {
assertPolar(vector)
return Vector.rectangular(Math.cos(vector.vector.a) * vector.vector.r, Math.sin(vector.vector.a) * vector.vector.r);
}
this.IsRectangular = function() { return this.vector.rep == Vector.representations.Rectangular; }
this.IsPolar = function() { return this.vector.rep == Vector.representations.Polar; }
this.Add = function (v2) {
assertVector(v2);
if (this.IsRectangular()) {
if (v2.IsPolar()) {
return this.Add(polar2Rect(v2));
}
return Vector.rectangular(this.vector.x + v2.vector.x, this.vector.y + v2.vector.y)
}
if (this.IsPolar()) {
return polar2Rect(this).Add(v2);
}
}
}
Vector.representations = { Rectangular: 0, Polar: 1 }
Vector.polar = function (r, a) {
return new Vector(Vector.representations.Polar, r, a)
}
Vector.rectangular = function (x,y) {
return new Vector(Vector.representations.Rectangular, x, y)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment