Skip to content

Instantly share code, notes, and snippets.

@arextar
Created September 18, 2011 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arextar/1225053 to your computer and use it in GitHub Desktop.
Save arextar/1225053 to your computer and use it in GitHub Desktop.
Unit

Unit.coffee

A quick scripts to support basic unit conversion in coffeescript and javascript. All you have to do is put one way conversion from one unit to another (for example: s to ms is 1000) and Unit.coffee handles bridging units (like converting ms to m) and going backwards in units. It does not yet support more complex conversions but this can be added by allowing a function to be set as the conversion factor (passing it a number, and whether it's forwards or reverse)

conversion=
"h m":60,
"m s":60,
"s ms":1000
path=(from,to)->
for c of conversion
if ~(" "+c+" ").indexOf(" "+from+" ")
c=c.split " ";
if c[0] is from
if conversion["#{c[1]} #{to}"]
c.push(to)
return c
else
return c.slice(0,-1).concat path c[1], to
throw "Cannot convert unit #{from} to unit #{to}.";
@Unit=class Unit
constructor:(@v, @u)->
convert:(u)->
return this if u is @u
if c=conversion[@u+" "+u]
v=@v*c
else if c=conversion[u+" "+@u]
v=@v*(1/c)
else
v=this
for un in path @u,u
v=v.convert(un)
v=v.v;
new Unit v, u;
toString:->
@v+@u
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment