Skip to content

Instantly share code, notes, and snippets.

@valikos
Last active August 29, 2015 14:19
Show Gist options
  • Save valikos/802b7b8c20e5b19f3688 to your computer and use it in GitHub Desktop.
Save valikos/802b7b8c20e5b19f3688 to your computer and use it in GitHub Desktop.
Practice task from "Eloquent Javascript"
var Vector = function(x, y) {
this.x = x;
this.y = y;
}
Vector.prototype.plus = function(vector) {
return new Vector.new(this.x + vector.x, this.y + vector.y)
}
Vector.prototype.minus = function(vector) {
return new Vector.new(this.x - vector.x, this.y - vector.y)
}
Object.defineProperty(Vector.prototype, 'length', {
get: function() {
var ax = Math.pow(this.x, 2);
var ay = Math.pow(this.y, 2);
return Math.sqrt(ax + ay)
}
});
console.log(new Vector(1, 2).plus(new Vector(2, 3)));
// Vector { x: 3, y: 5 }
console.log(new Vector(1, 2).minus(new Vector(2, 3)));
// Vector { x: -1, y: -1 }
console.log(new Vector(3, 4).length);
// 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment