Skip to content

Instantly share code, notes, and snippets.

@bchartoff
Created August 5, 2015 00:40
Show Gist options
  • Save bchartoff/9e92be611f2f67a78d06 to your computer and use it in GitHub Desktop.
Save bchartoff/9e92be611f2f67a78d06 to your computer and use it in GitHub Desktop.
function niceUnits(tspEquiv){
var tblspEquiv;
if(tspEquiv < 3){ return tspEquiv + " teaspoon" + plural(tspEquiv);}
else{
tblspEquiv = parseFloat(tspEquiv)/3.0;
if (tblspEquiv < 4){
var remainder = (tspEquiv%3 == 0) ? "" : " and " + niceUnits(tspEquiv%3)
return Math.floor(tblspEquiv) + " tablespoon" + plural(Math.floor(tblspEquiv)) + remainder;
} else{
cupEquiv = parseFloat(tblspEquiv/16.0);
}
if((cupEquiv * 4)%1==0){
var base = (Math.floor(cupEquiv) == 0) ? "" : Math.floor(cupEquiv);
var remainder;
switch(cupEquiv - base){
case .25:
remainder = '\u00BC';
break;
case .5:
remainder = '\u00BD';
break;
case .75:
remainder = '\u00BE';
break;
case 0:
remainder = "";
break;
}
return base + remainder + " cup" + plural(cupEquiv)
}
else if((cupEquiv * 3)%1==0){
var base = (Math.floor(cupEquiv) == 0) ? "" : Math.floor(cupEquiv);
var remainder = (cupEquiv - base < .4) ? '\u2153' : '\u2154'; //unicode 1/3 and 2/3, respectively
return base + remainder + " cup" + plural(cupEquiv)
} else{
var quarterRemainder = niceUnits(tspEquiv%12)
var thirdRemainder = (tspEquiv%16 < 16 && tspEquiv%16 > 12) ? "and" : niceUnits(tspEquiv%16)
if(quarterRemainder.indexOf("and") != -1 && thirdRemainder.indexOf("and") == -1){
return niceUnits(tspEquiv - tspEquiv%16) + " and " + thirdRemainder;
}
else if(quarterRemainder.indexOf("and") == -1 && thirdRemainder.indexOf("and") != -1){
return niceUnits(tspEquiv - tspEquiv%12) + " and " + quarterRemainder;
} else{
return niceUnits(tspEquiv - tspEquiv%12) + " and " + quarterRemainder;
}
}
}
function plural(unit){
if (unit == 1 || unit < 1) {return ""}
else{ return "s"}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment