Skip to content

Instantly share code, notes, and snippets.

@asarode
Last active August 29, 2015 14:25
Show Gist options
  • Save asarode/120f0f923ab31ad8e730 to your computer and use it in GitHub Desktop.
Save asarode/120f0f923ab31ad8e730 to your computer and use it in GitHub Desktop.
Some snippets that show how some open source projects first started out
/*
* Initial steps of the mateogianolio/vectorious library
* https://github.com/mateogianolio/gravity/blob/master/js/vector.js
*/
function Vector(x, y) {
this.x = x;
this.y = y;
}
// Addition
Vector.prototype.add = function(vector) {
return new Vector(this.x + vector.x, this.y + vector.y);
};
// Subtraction
Vector.prototype.subtract = function(vector) {
return new Vector(this.x - vector.x, this.y - vector.y);
};
// Dot product
Vector.prototype.dot = function(vector) {
return (this.x * vector.x + this.y * vector.y);
}
// Scaling
Vector.prototype.scale = function(c) {
return new Vector(this.x * c, this.y * c);
}
// Calculation of magnitude
Vector.prototype.magnitude = function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
// Calculation of unit vector
Vector.prototype.unitvector = function() {
var mag = this.magnitude();
if(mag != 0)
return new Vector(this.x / mag, this.y / mag);
return new Vector(0, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment