Vector.js: A simple vector class in ES6
Recently I built a vector class in Ecmascript 6 for some coursework that I've been writing, and I thought that I'd share it here. I found out a little while ago that chrome does actually support classes, so long as you enable strict mode. After looking into them, they are actually really useful when writing a HTML5 canvas demo, or writing a reusable library. I'll make a post on how to use them sometime soon (as soon as I have time).
Anyway, the class that I wrote supports addition, subtraction, division, multiplication, length limitation (preserving direction), the dot product, angle from another vector, unit vector calculation, length calculation, and cloning. Here's the code:
You can create instances of this class as you would any other:
var v = new Vector(100, 100), // Create a new vector for the point (100, 100) v2 = new Vector(300, 400); // Vector for the point (300, 400) // Clone v and subtracts v2 from it, putting the result into v3. // Note that `add()`, `subtract()`, etc. are _mutators_. v3 = v.clone().subtract(v2);
If I've missed any functionality, please feel free to leave a request in a comment below. Even better - fork the gist and implement it yourself! I'd love to pull in your changes. Feel free to use this class in your own projects. A link back isn't required, but very much appreciated!
That's about everything I have to say about this class, but I'll be posting a bezier curve class soon that depends on this one - probably sometime next week. Bye!
Update 24th January 2016: I've replaced the original code with an embedded version of the gist in order to keep it up to date, since I've revised it slightly sinec writing this blog post.