Created
February 28, 2018 12:26
-
-
Save jonurry/153b99d792d42345cf2c672b1f9fe84a to your computer and use it in GitHub Desktop.
6.1 A Vector Type (Eloquent JavaScript Solutions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Vec { | |
constructor (x, y) { | |
this.x = x; | |
this.y = y; | |
} | |
plus(v) { | |
return new Vec(this.x + v.x, this.y + v.y); | |
} | |
minus(v) { | |
return new Vec(this.x - v.x, this.y - v.y); | |
} | |
get length() { | |
return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); | |
} | |
} | |
console.log(new Vec(1, 2).plus(new Vec(2, 3))); | |
// → Vec{x: 3, y: 5} | |
console.log(new Vec(1, 2).minus(new Vec(2, 3))); | |
// → Vec{x: -1, y: -1} | |
console.log(new Vec(3, 4).length); | |
// → 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hints
Look back to the
Rabbit
class example if you’re unsure howclass
declarations look.Adding a getter property to the constructor can be done by putting the word get before the method name. To compute the distance from (0, 0) to (x, y), you can use the Pythagorean theorem, which says that the square of the distance we are looking for is equal to the square of the x-coordinate plus the square of the y-coordinate. Thus, √(x2 + y2) is the number you want, and
Math.sqrt
is the way you compute a square root in JavaScript.