====== Steve Wang: Nutrition calculator ====== By: [[steve-wang|Steve Wang]] ===== Writing ===== 10.9 million deaths were due to poor diets in 2017. Health Data also reports that 22% of all deaths among adults in 2017, with cardiovascular disease (CVD) as the leading cause, followed by cancers and diabetes. Not only do poor diets cause deaths, they have also resulted in 255 million disability-adjusted life years. It equates to the sum of years of life lost and years lived with disability (IHME, 2019). This indicates that it is very important to have a healthy diet. To avoid the same fate they met, we need to explore how we can have a healthy diet, what methods we can use and how to use those methods. The logical next question is, how do I tell if a diet is healthy. There are many factors but according to Gundersen Health System, one important factor is checking if the food eaten provides the nutrients the body needs (Gundersen Health System). If you are like most people, you do not go and check what the nutritional content in everything you eat is. Which is normal and understandable because it takes a large amount of time to do so. Most of the time if we get food we just want to eat it. However, it is very important to know the nutrients of the food you are eating. It is especially important for people like me, who have diabetes. Before, I would just eat what I want and I cannot control my insulin intake very well. If I do not take the right amount of insulin, it might cause some health issues for me. So, I have made a program that helps me with my issues. This program will help add up how many of what nutrients are in a dish once you key them in. The nutrients it will check for are calories, protein, fat, carbohydrates, iron, calcium, fiber, sodium, and vitamin D. In the program, they should also be entered in this order. Additionally. It will also help you check if you are having too much of any nutrient. Which will allow you to change your dish to ensure a healthy meal. This program mainly focuses on calories because too many calories might make you fat (NHS, 2019). To most people, weight is very important. So, the program can tell you where the calories come from. What percentage of calories come from which ingredient to battery helps you pick which ingredient to eat less of. When the program gets all the information it needs, it prints out a neat and easily-readable report so that you can easily find out what to change about your dish or meal. Using this tool, I can stop being lazy and start calculating which will hopefully allow me to calculate how much insulin to take. However, I still have to enter the information needed for the program to work. After the information is entered, the program will calculate the percentage of each nutrient in the ingredient. Then it will tell you how many grams of each nutrient are in a specific amount of each ingredient. If I am going to use it, I must be able to trust it. So, when I was making this, I made sure to do research on how much of each nutrient listed in the calculator you need in a meal. Doing so, I found out how unhealthy my diet was. I then had to learn some new things about percentages. This calculator has also been checked on dishes like fried rice and smoothies. Now, I can use this to find out how much carbohydrates I eat which is what mainly affects my sugar level. Doing so will allow me to control my sugar level better. Other than that, I can also ensure that I eat a healthy diet. There are still many more things that can and should be added to the program. However I think the first step should be a better user interface which will come at a later date because I had already had a lot of problems making the current version and I had also learnt a lot about objects. IN general doing this has made me realize how little I knew about programming and how much more I have to learn to perfect this calculator. After writing about the importance of diet, telling you about the program and the benefits of using it. I encourage you to use this program or some or some type of program or calculator that does the same thing to ensure you have a healthy diet. Let us learn from the other's who have fallen prey to the trap of unhealthy diets. Learn from them so that we do not make the same mistakes. This program is available to anyone who wants to use it for their own well being. ===== Citation ===== 1. IHME. (2019, April 3). New study finds poor diet kills more people globally than tobacco and high blood pressure | Institute for Health Metrics and Evaluation. IHME. https://www.healthdata.org/news-release/new-study-finds-poor-diet-kills-more-people-globally-tobacco-and-high-blood-pressure 2. Gundersen Health System. (n.d.). How to know if you’re really eating healthy—Gundersen Health System. Gundersen Health System. Retrieved June 12, 2022, from https://www.gundersenhealth.org/health-wellness/eat/how-to-know-if-youre-really-eating-healthy/ 3. NHS. (2019, August 23). Understanding calories—NHS. NHS. https://www.nhs.uk/live-well/healthy-weight/managing-your-weight/understanding-calories/ ===== Code ===== To use this code, you can use the browser console on your computer or any other console that runs JavaScript. To run this in the console, copy all the code in the code box below. On your computer, press CTRL/CMD+shift+i or f12. You should see something appear and inside that console paste all the code and press enter. Then you should see the correct output. //====== Nutrient Calculator Revised ====== //The total weight is correct //Check if this thing inside string is a letter: function checkForLetter(inputCharacter) { if (inputCharacter.length != 1) { return 'Please give 1 character!' } let letters = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm'] let inputType = false letters.forEach(x => { if (x == inputCharacter) { inputType = true } }) letters.forEach((x, i) => { letters[i] = letters[i].toUpperCase() }) if (inputType == false) { letters.forEach(x => { if (x == inputCharacter) { inputType = true } }) } return inputType } function roundOff (number,decimalPlaces){ if (typeof number=='number'){ let roundedNumber=number.toFixed(decimalPlaces); return JSON.parse(roundedNumber)} else{return number}} //Normal text to Title case: function titleCase(inputString) { //The input string should be in proper English. To Make sure a word does not get capitalized put * infront of it. inputString = inputString.split('') inputString.forEach((x, i) => { if (inputString[i - 1] == ' ' || inputString[i - 1] == '\n') { inputString[i] = inputString[i].toUpperCase() } }) inputString[0] = inputString[0].toUpperCase() inputString = inputString.join('') inputString = inputString.replaceAll('*', '') return inputString } //Camel case to normal text: function unCammelCase (inputString){ //Code will make sure the first letter of a word is capitalized if there is * infront of it. Ex: *Bob. Code will also automatically make a stand alone 'i' capitalized. code will also add punctuation to the end of string if there is none there. if (inputString!=inputString.toLowerCase()){ let allLower=inputString.toLowerCase().split('') let splitInput=inputString.split('') allLower.forEach((x,i)=>{ if (x!=splitInput[i] && splitInput[i-1]!=' '){ if (splitInput[i-1]=='*'){ if (checkForLetter(splitInput[i-2]==true)){ splitInput=safeSplice(splitInput,1,i,' '+ splitInput[i])} } else{ if (checkForLetter(splitInput[i-1]==true)){ splitInput=safeSplice(splitInput,1,i,' '+ splitInput[i].toLowerCase())} else { splitInput=safeSplice(splitInput,1,i,splitInput[i].toLowerCase())} } if (splitInput[i]==' i '){ splitInput[i]=splitInput[i].toUpperCase()} } if (isNaN(splitInput[i])==false && isNaN(splitInput[i-1])==true && splitInput[i]!=' '){ if (splitInput[i-1]!='.'){ splitInput=safeSplice(splitInput,1,i,' '+ splitInput[i])}} }) splitInput=splitInput.join('') if (checkForLetter(splitInput[splitInput.length-1])==true){ if (splitInput.includes('I') || splitInput.includes('*')){ splitInput+='.' } else{ splitInput+=':' }} splitInput=splitInput.replaceAll('*','') return splitInput } else { return 'Text input not in proper camel case form.' }} function totals(array) { let totalItems = {} let props = Object.keys(array) for (let a in array[props[0]]) { totalItems[a] = 0 } for (let b in totalItems) { let totalAmount = 0 for (let i = 0; i < array.length; i++) { totalAmount += array[i][b] } totalItems[b] = totalAmount; } delete totalItems.itemName return totalItems } function safeSplice(inputArray, amountToRemove, indexToRemove, replaceWith) { let array1 = inputArray.slice(0, indexToRemove) if (replaceWith != undefined) { array1.push(replaceWith) } let array2 = inputArray.slice(indexToRemove + amountToRemove, inputArray.length) return array1.concat(array2) } class NutritionData { constructor(name, calories, protein, fat, carbs, iron, calcium,fiber,sodium,vitaminD) { //Percentage of each nutrient //Add calories this.ingredientName = name; console.log(this.ingredientName) this.amount = 100; this.calories = calories this.protein = protein; this.fat = fat; this.carbs = carbs; this.iron = iron; this.calcium = calcium; this.fiber=fiber this.sodium=sodium this.vitamindD=vitaminD return { itemName: this.ingredientName, weightInGrams: this.amount, caloriesIn100g: (this.calories / this.amount) *this.amount, proteinPercent: (this.protein / this.amount) * this.amount, fatPercent: (this.fat / this.amount) * this.amount, carbsPercent: (this.carbs / this.amount) * this.amount, ironPercent: (this.iron / this.amount) * this.amount, calciumPercent: (this.calcium / this.amount) * this.amount, fiberPercent: (this.fiber / this.amount) * this.amount, sodiumPercent: (this.sodium / this.amount) * this.amount, vitaminDPercent: (this.vitamindD / this.amount) * this.amount, } } } class Ingredients { //calculate the real gram amount constructor(amount, nutritionDataObject) { this.itemName = nutritionDataObject.itemName this.Calories = ((nutritionDataObject.caloriesIn100g) / nutritionDataObject.weightInGrams) * amount this.Protein = ((nutritionDataObject.proteinPercent) / nutritionDataObject.weightInGrams) * amount this.Fat = ((nutritionDataObject.fatPercent) / nutritionDataObject.weightInGrams) *amount this.Carbs = ((nutritionDataObject.carbsPercent) / nutritionDataObject.weightInGrams) * amount this.Iron = ((nutritionDataObject.ironPercent) / nutritionDataObject.weightInGrams) * amount this.Calcium = ((nutritionDataObject.calciumPercent) / nutritionDataObject.weightInGrams) * amount this.Fiber = ((nutritionDataObject.fiberPercent) / nutritionDataObject.weightInGrams) * amount this.sodium = ((nutritionDataObject.sodiumPercent) / nutritionDataObject.weightInGrams) * amount this.vitaminD= ((nutritionDataObject.vitaminDPercent) / nutritionDataObject.weightInGrams) * amount this.totalWeight = amount } } class Dish { constructor(name, arrayOfIngredientObjects) { this.nameOfDish = name; this.weight = totals(arrayOfIngredientObjects).weightInGrams this.totalIngredients = totals(arrayOfIngredientObjects) this.ingredients = arrayOfIngredientObjects } } class Serving { constructor(name, arrayOfIngredientObjects) { //Make a serving thing. this.nameOfDish = name this.weight = totals(arrayOfIngredientObjects).itemAmount this.allNutrients = JSON.parse(JSON.stringify(totals(arrayOfIngredientObjects))) } suggestedServing(weight) { //weight= body weight in kg //This hting is in grams let recomended = { protein: (0.8 * weight) / 5, calories: 311.034768 / 5, iron: 0.003, calcium: 0.2, } recomended.carbs = (recomended.calories * (55 / 100)) / 5, recomended.fat = (recomended.calories * (26 / 100)) / 5, console.log(this.nameOfDish, 'Nutrition Data:') console.log('This is the serving size:', JSON.stringify(this.allNutrients.totalWeight) + 'g.') delete this.allNutrients.totalWeight for (let i in this.allNutrients) { if (i != 'Calories') { this.allNutrients[i] = JSON.stringify(this.allNutrients[i]) + 'g' } } let fixedAllNutrients = JSON.stringify(this.allNutrients) fixedAllNutrients = fixedAllNutrients.replace('{', '') fixedAllNutrients = fixedAllNutrients.replace('}', '') for (let i in this.allNutrients) { fixedAllNutrients = fixedAllNutrients.replace(',', '\n') fixedAllNutrients = fixedAllNutrients.replace('"', '') fixedAllNutrients = fixedAllNutrients.replace('"', '') fixedAllNutrients = fixedAllNutrients.replace('"', '') fixedAllNutrients = fixedAllNutrients.replace('"', '') } console.log('Here is the total amount of nutrients in the ' + this.nameOfDish + ':\n' + fixedAllNutrients) if (this.allNutrients.proteinPercent < recomended.protein - 2 || this.allNutrients.proteinPercent > recomended.protein) { console.log('Protein out of range') } if (this.allNutrients.fatPercent < recomended.fat - 2 || this.allNutrients.fatPercent > recomended.fat) { console.log('Fat out of range') } if (this.allNutrients.caloriesIn100g < recomended.calories - 2 || this.allNutrients.caloriesIn100g > recomended.calories) { console.log('Calories out of range') } if (this.allNutrients.carbsPercent < recomended.carbs - 2 || this.allNutrients.carbsPercent > recomended.carbs) { console.log('Carbs out of range') } if (this.allNutrients.ironPercent < recomended.iron - 2 || this.allNutrients.ironPercent > recomended.iron) { console.log('Iron out of range') } if (this.allNutrients.calciumPercent < recomended.calcium - 2 || this.allNutrients.calciumPercent > recomended.calcium) { console.log('Calcium out of range') } } } class BeautifulOutput { constructor(inputGrams, inputPercent, dishName,serving) { this.serving=serving if (this.serving==0){ this.serving=1 } this.dishName = dishName this.inputGrams = JSON.parse(JSON.stringify(inputGrams)) this.gramOutput = JSON.parse(JSON.stringify(totals(inputGrams))); this.gramOutputSave = JSON.parse(JSON.stringify(totals(inputGrams))); delete this.gramOutput.dishName for (let i in this.gramOutput) { if (i != 'Calories') { this.gramOutput[i] = JSON.stringify(this.gramOutput[i]/this.serving) + 'g' } else{ this.gramOutput[i] = JSON.stringify(this.gramOutput[i]/this.serving) + ' calories' } } this.gramOutput = JSON.stringify(this.gramOutput) this.gramOutput = this.gramOutput.replace('{', '') this.gramOutput = this.gramOutput.replace('}', '') this.gramOutput = this.gramOutput.replaceAll(',', '\n') this.gramOutput = this.gramOutput.replaceAll('"', '') this.gramOutput = this.gramOutput.replaceAll(':', ': ') this.inputPercent = JSON.parse(JSON.stringify(inputPercent)); this.gramOutput=this.gramOutput.toLowerCase() this.finalgramOutput = 'The total amount of nutrients in the ' + this.dishName + ' in grams is: \n' + this.gramOutput this.finalgramOutput=this.finalgramOutput.replace('vitamind','vitamin D') } calculateTotals() { this.doGrams() this.doPercents() console.log('Here is the list of ingredients in the', this.dishName,':') this.inputGrams.forEach((x,i)=>{ console.log(i+1+') '+x.itemName+': '+ this.inputGrams[i].totalWeight+'g')}) console.log(this.finalgramOutput) return this } doGrams() { this.convertInputGrams=JSON.parse(JSON.stringify(this.inputGrams)) this.convertInputGrams = safeSplice(this.convertInputGrams, 0, 0, 'The weight in grams of nutrients in each ingredient is:\n') //console.log('inpautGrams',this.convertInputGrams) this.convertInputGrams.forEach(x => { if (typeof x == 'string') { x=x.replaceAll(':',': ') console.log(x) } else { for (let i in x) { if (i != 'itemName' && i != 'Calories') { x[i] = JSON.stringify(roundOff(x[i],2)/this.serving) + 'g' } if (i=='Calories'){ x[i] = JSON.stringify(x[i]/this.serving) + ' calories'} if (i=='itemName'){ x[i]=x[i].replaceAll(':',': ') }}} let output = JSON.stringify(x) output = output.replace('{', '') output = output.replace('}', '') for (let i = 0; i < output.length; i++) { output = output.replace(',', '\n') output = output.replace('"', '') } output=output.replaceAll(':',': ') let doneUnCammeling = unCammelCase(output) doneUnCammeling=doneUnCammeling.replaceAll('vitamin d','vitamin D') console.log(doneUnCammeling + '\n') }) } doPercents() { this.convertInputPercent=JSON.parse(JSON.stringify(this.inputPercent)) this.convertInputPercent = safeSplice(this.convertInputPercent, 0, 0, 'The percentage of each nutrients inside the ingredient is : \n ') this.convertInputPercent.forEach(x => { if (typeof x == 'string') { console.log('here string', x) x=x.replaceAll(':',': ') console.log(x) } else { for (let i in x) { if (i=='weightInGrams') { x[i] = JSON.stringify(roundOff(x[i],2)/this.serving) + 'g' } if (i=='caloriesIn100g'){ x[i] = JSON.stringify(roundOff(x[i],2)/this.serving) + ' calories' } if (i=='itemName'){ x[i]=x[i].replaceAll(':',': ') }}} let output = JSON.stringify(roundOff(x,2)) output = output.replace('{', '') output = output.replace('}', '') for (let i = 0; i < output.length; i++) { output = output.replace(',', '\n') output = output.replace('"', '') } output=output.replaceAll(':',': ') let doneUnCammeling = unCammelCase(output) doneUnCammeling=doneUnCammeling.replaceAll('vitamin d','vitamin D') console.log(doneUnCammeling + '\n') })} partsOfCalories(){ let calories=this.gramOutputSave.Calories console.log('Here is the percentage of each nutrient from the total calories.\n') console.log('Total calories: ' + JSON.stringify(calories)) console.log('From protein:' + JSON.stringify((this.gramOutputSave.Protein/calories)*100)+'\n') console.log('From carbs:' + JSON.stringify((this.gramOutputSave.Carbs/calories)*100)+'\n') console.log('From fat:' + JSON.stringify((this.gramOutputSave.Fat/calories)*100)+'\n') } calculateCalories(){ this.calculatingCalories = JSON.parse(JSON.stringify(this.inputGrams)) this.totalCalories=totals(JSON.parse(JSON.stringify(this.inputGrams))) this.calculatingCalories.forEach(x=>{ console.log('The percentage of calories in', this.dishName, 'from',x.itemName,'is',(x.Calories/this.totalCalories.Calories)*100,'%.') }) }} friedRiceNutritionData = [] //Butter: friedRiceNutritionData.push(new NutritionData('unsalted butter', 717, 0.9, 81.1, 0.1,0,0.024 ,0,0.011,0)) //egg friedRiceNutritionData.push(new NutritionData('egg (raw)', 143, 12.6, 9.5, 0.7,0.0018,0.056,0,0.142,1e-6)) //Carrots: friedRiceNutritionData.push(new NutritionData('carrots', 41, 0.9, 0.2, 9.6,0.0003,0.033,2.8,0.069,0)) //Onion: friedRiceNutritionData.push(new NutritionData('onions', 40,1.1,0.1, 9.3,0.0002 , 0.023,1.7,0.004,0)) //Peas: friedRiceNutritionData.push(new NutritionData('peas', 81, 5.4, 0.4, 14.5, 0.0015, 0.025,5.7,0.005,0)) //Garlic: //constructor(name, calories, protein, fat, carbs, iron, calcium,fiber,sodium,vitaminD) friedRiceNutritionData.push(new NutritionData('garlic', 149,6.4,0.5,33.1,0.0017,0.181,2.1,0.017,0)) //Rice: friedRiceNutritionData.push(new NutritionData('cooked white rice', 130, 2.7, 0.3, 28.2, 0.0012, 0.01,0.4,0.001,0)) //Green Onions: friedRiceNutritionData.push(new NutritionData('Growers Marketing LLC - Fresh Green Onions', 40, 0,0,8,0.0014,0.08,4,0.04,0)) //Soy sauce friedRiceNutritionData.push(new NutritionData('soy sauce', 53, 8.1,0.6, 4.9,0.0015 , 0.033,0.8,5.493,0)) //Oyster Sauce: friedRiceNutritionData.push(new NutritionData('Oyster Sauce',127,5.5,8.1,7.8,0.0036,0.079,0.2,0.242,6e-7)) //Sesame Oil friedRiceNutritionData.push(new NutritionData('Sesame Oil',884,0,100,0,0,0,0,0,0)) friedRiceGrams = [] //butter friedRiceGrams.push(new Ingredients(42, friedRiceNutritionData[0])) //Eggs friedRiceGrams.push(new Ingredients(88, friedRiceNutritionData[1])) //Carrots friedRiceGrams.push(new Ingredients(120, friedRiceNutritionData[2])) //Onion friedRiceGrams.push(new Ingredients(125, friedRiceNutritionData[3])) //Peas friedRiceGrams.push(new Ingredients(70, friedRiceNutritionData[4])) //Garlic: friedRiceGrams.push(new Ingredients(18, friedRiceNutritionData[5])) //Rice friedRiceGrams.push(new Ingredients(744, friedRiceNutritionData[6])) //Onion: friedRiceGrams.push(new Ingredients(36, friedRiceNutritionData[7])) //Soy Suace: friedRiceGrams.push(new Ingredients(56, friedRiceNutritionData[8])) //Oyster Sauce: friedRiceGrams.push(new Ingredients(12, friedRiceNutritionData[9])) //Sesame Oil: friedRiceGrams.push(new Ingredients(2.25, friedRiceNutritionData[10])) //Organized Grams: friedRiceOrganizedGrams = new Dish('fried rice', friedRiceGrams) //Organized Percent: friedRiceOrganizedPercent = new Serving('fried rice', friedRiceGrams).suggestedServing(100) //Beautiful Outputs: let friedRiceTotals; function getTotals() { friedRiceTotals = new BeautifulOutput(friedRiceGrams, friedRiceNutritionData, 'fried rice',5).calculateTotals() } //friedRiceTotals.calculateCalories() getTotals() /* Source of protein: https://www.health.harvard.edu/blog/how-much-protein-do-you-need-every-day-201506188096 Source of calories: https://www.calculator.net/calorie-calculator.html#:~:text=Though%20it%20differs%20depending%20onthe%20U.S%20Department%20of%20Health. Source of Carbs: https://www.mayoclinic.org/healthy-lifestyle/nutrition-and-healthy-eating/in-depth/carbohydrates/art-20045705#:~:text=How%20many%20carbohydrates%20do%20yougrams%20of%20carbs%20a%20day. Source of Fat: https://blog.nasm.org/how-many-grams-of-fat-per-day-to-lose-weight#:~:text=According%20to%20the%20Dietary%20Guidelines34%2D68g%20fat%20per%20day. Source of Iron: webmd.com/diet/supplement-guide-iron Source of Calcium: https://www.betterhealth.vic.gov.au/health/healthyliving/calcium */