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)
Created
September 18, 2011 13:06
-
-
Save arextar/1225053 to your computer and use it in GitHub Desktop.
Unit
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
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