Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Asmageddon/1b44d7a5487fec241c9e to your computer and use it in GitHub Desktop.
Save Asmageddon/1b44d7a5487fec241c9e to your computer and use it in GitHub Desktop.
var WOLFRAM_KEY = "<API KEY GOES HERE>";
var local_cache = {};
function wolfram_api_call(query, key) {
var response = UrlFetchApp.fetch("http://api.wolframalpha.com/v2/query?input=" + encodeURIComponent(query) + "&appid=" + key + "&format=plaintext");
var xml = XmlService.parse(response);
var root = xml.getRootElement();
return root;
}
function _get_pod_plaintext(xml) {
var success = xml.getAttribute("success");
if (success) {
var children = xml.getChildren();
for (var i = 0; i < children.length; i++) {
var elem = children[i];
var title_attr = elem.getAttribute("title");
if (title_attr != null && title_attr.getValue() == "Average nutrition facts" || title_attr.getValue() == "Nutrition facts") {
return elem.getChild("subpod").getChild("plaintext").getText();
}
}
return null;
} else {
return null;
}
}
function _weight_unit_mult(unit_str) {
if(unit_str == "g") { return 1; }
if(unit_str == "mg") { return 0.001; }
if(unit_str == "kg") { return 1000; }
}
function _get_plaintext(food) {
var cache = CacheService.getPublicCache();
var cached = cache.get("wa_food_data_" + food)
var text = null;
if (cached != null && cached != "") {
text = cached;
} else {
var xml = wolfram_api_call("1000g " + food + " food", WOLFRAM_KEY);
text = _get_pod_plaintext(xml);
cache.put("wa_food_data_" + food, text, 7 * 24 * 60 * 60);
}
return text;
}
function _wolfram_nutrition_facts(food) {
var text = _get_plaintext(food);
var calories=0, fat=0, carbs=0, protein=0;
var lines = text.split(/\r?\n/);
for(var i=0; i < lines.length; i++) {
var line = lines[i];
var split_line = line.split(" ").filter(function(e) { return e != ""; } );
if (line.match("total calories") != null) {
calories = split_line[2] * 0.001;
} else if (line.match("total fat") != null) {
fat = split_line[2] * _weight_unit_mult(split_line[3]) * 0.001;
} else if (line.match("total carbohydrates") != null) {
carbs = split_line[2] * _weight_unit_mult(split_line[3]) * 0.001;
} else if (line.match("protein") != null) {
protein = split_line[1] * _weight_unit_mult(split_line[2]) * 0.001;
}
}
return [calories, fat, carbs, protein];
}
function _nutrition_data(food) {
if (food == "" || food == null) { return ["", "", "", ""]; }
if (local_cache[food] == null) {
local_cache[food] = _wolfram_nutrition_facts(food);
}
return local_cache[food];
}
// Actual methods to use. Unit is grams
function calories(food) {
return _nutrition_data(food)[0];
}
function fat(food) {
return _nutrition_data(food)[1];
}
function carbs(food) {
return _nutrition_data(food)[2];
}
function protein(food) {
return _nutrition_data(food)[3];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment