Skip to content

Instantly share code, notes, and snippets.

@ayrusme
Last active December 5, 2021 17:40
Show Gist options
  • Save ayrusme/06c09db4f2e395add3f1eed79ab94d86 to your computer and use it in GitHub Desktop.
Save ayrusme/06c09db4f2e395add3f1eed79ab94d86 to your computer and use it in GitHub Desktop.
const calorieMap = {};
function calculateCalories() {
let spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
let calorieSheet = spreadsheet.getSheetByName("Calories");
let calorieValues = calorieSheet.getRange("A2:B").getDisplayValues();
for (let [index, item] of calorieValues.entries()) {
if (item[0].length && item[1].length) {
calorieMap[item[0].trim()] = parseFloat(item[1].trim());
} else {
break;
}
}
let sheet = spreadsheet.getSheetByName("Calorie Tracker");
let data = sheet.getRange("B2:B").getDisplayValues();
let outputRange = sheet.getRange("C2:C");
let outputValues = [];
for (let [index, value] of data.entries()) {
if (!value || !value[0].length) {
outputValues.push([[]]);
continue;
}
let foods = value[0].split(",");
let calories = 0;
for (let [idx, food] of foods.entries()) {
let [foodName, consumed] = food.split("-");
if (calorieMap[foodName]) {
calories += calorieMap[foodName] * parseFloat(consumed);
}
}
outputValues.push([calories]);
}
outputRange.setValues(outputValues);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment