Skip to content

Instantly share code, notes, and snippets.

@jacksonwillis
Created May 11, 2012 18:33
Show Gist options
  • Save jacksonwillis/2661565 to your computer and use it in GitHub Desktop.
Save jacksonwillis/2661565 to your computer and use it in GitHub Desktop.
CoffeeScript Vector Math
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