Created
May 11, 2012 18:33
-
-
Save jacksonwillis/2661565 to your computer and use it in GitHub Desktop.
CoffeeScript Vector Math
This file contains 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
Number::toRadians = -> (@ * Math.PI) / 180 | |
Number::toDegrees = -> (@ * 180) / Math.PI | |
Array::product = -> @reduce (a, e) -> a * e | |
Array::sum = -> @reduce (a, e) -> a + e | |
Array::zip = (args...) -> ((args...) -> | |
longest = args.reduce ((a, b) -> (if a.length > b.length then a else b)), [] | |
longest.map (_, i) -> args.map (array) -> array[i])(@, args...) | |
# | |
class Vector | |
constructor: (@x = 0, @y = 0, @z = 0) -> | |
inspect: -> "#<Vector <#{@toArray().join ", "}>>" | |
toArray: -> [@x, @y, @z] | |
# returns boolean | |
zero_p: -> @toArray().every (e) -> e is 0 | |
# returns scalar | |
dot: (other) -> (@toArray().zip(other.toArray()).map (e) -> e.product()).sum() | |
# returns scalar | |
magnitude: -> Math.sqrt @dot @ | |
# returns angle measurement (radians) | |
angleBetween: (other) -> Math.acos (@dot other) / (@magnitude() * other.magnitude()) | |
alert (new Vector 1, 2, 3).angleBetween(new Vector 3, 4, 5).toDegrees() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment