Dev.to WebDev ๐Ÿ›  Dev ๐Ÿ‘ 0 ๐Ÿ“– 7 min read

Building a Recipe Calorie Calculator: Why Cooked Weight Matters

Add up the calories in the ingredients, weigh the finished dish without the container, then calculate what fraction of the dish you served. If the recipe contains 360 kcal and your serving weighs half of the finished dis

Add up the calories in the ingredients, weigh the finished dish without the container, then calculate what fraction of the dish you served. If the recipe contains 360 kcal and your serving weighs half of the finished dish, it contains 180 kcal. This calculation assumes the calorie-containing ingredients stayed in the dish and are distributed reasonably evenly.

The formula is the easy part. The food database is what makes this a usable calculator. If users have to hunt down the calories for every ingredient themselves, they still have most of the work to do.

Key takeaways

  • Use an ingredient weight and a nutrition entry that describe the same state of the food.

  • Use the finished dish's weight as the denominator for both per-serving and per-100 g results.

  • A blank input and a valid value of 0 kcal per 100 g have different meanings.

  • Keep intermediate values unrounded and format the result for display.

  • Cooked weight alone cannot tell you how much oil or broth was discarded.

How did half the pot end up with 540 kcal?

Take a one-ingredient test recipe. The ingredient entry is 100 g of dry grain at 360 kcal per 100 g. The measured cooked yield is 300 g. The water adds weight, and assuming none of the grain is discarded, the pot still contains 360 kcal. A 150 g serving is half the pot. How could it contain more calories than the whole thing?

The mistake is dividing 360 kcal by the 100 g dry weight and multiplying by 150 g of cooked grain. The calculator treats 150 g as one and a half recipes, even though it represents half of the finished dish. Here's how the numbers work out in this hypothetical example.

Amount Calculation Result
Whole recipe 100 ร— 360 รท 100 360 kcal
Per 100 g cooked 360 ร— 100 รท 300 120 kcal
150 g serving 360 ร— 150 รท 300 180 kcal

1. Calculate calories for the whole recipe

For each ingredient, multiply its weight by its calories per 100 g, divide by 100, then add the results. If you weighed dry grain, use the dry-grain entry. If you added grain that was already cooked, use the cooked entry. It's easy to pick the wrong entry from a database, and that error is already in your total before you calculate the serving.

Recipe calories = ฮฃ (ingredient weight in g ร— kcal per 100 g รท 100)

2. Scale by the finished weight

The model takes the net weight of the cooked dish, excluding the container. Divide the serving weight by the weight of the whole dish. Multiply the recipe's calories by that fraction. For the per-100 g result, use 100 in place of the serving weight. Protein, fat, and carbohydrates scale the same way once you have their totals for the recipe.

Serving calories = recipe calories ร— serving weight รท cooked dish weight

There are two separate questions here. How much does the dish weigh after cooking? How much of each nutrient is still in it? Water can evaporate while the ingredients stay in the pot, whereas discarded broth can take nutrients with it. Food composition methods account for cooked yield and nutrient retention separately. Recipe calculation methods, section on multicomponent foods

The math is the easy part. Where do you get the food data?

Say someone is logging a recipe with rice, chicken, and a store-bought sauce. If search finds the rice and chicken but the sauce has no calorie data, the calculator can still show a number that looks complete. The user either has to look up the sauce by hand or gets a total with an ingredient missing.

Choose the food API early. Check whether it finds the products people actually buy, whether the records include calories per 100 g, and whether you can tell raw ingredients from cooked ones. A barcode match without usable nutrition data is still a dead end for the calculation. When a value is missing, show which ingredient needs attention and let the user enter it from the label.

API Access and pricing Coverage and trade-offs
Open Food Facts Free, with rate limits. Read requests do not require authentication. Community-maintained database of packaged foods worldwide. Some products or calorie values are missing. The database is licensed under ODbL.
Expotion Food API Free with attribution to Expotion as the data source. Request access and documentation separately. Each application is reviewed individually. Food search, barcode lookup, and nutrition data. Coverage is incomplete.
fatsecret Platform API Basic is free for up to 5,000 calls per day and covers the US. Paid Premier pricing is quoted by market. There is also a US-only Premier Free tier for eligible applicants. Paid Premier lists more than 62 countries and unlimited API calls. Start here if you need broad international coverage and have a budget for it.

Try Open Food Facts and Expotion as complementary lookup sources. A product missing from one of them may show up in the other. Check the terms before merging either dataset into a shared catalog. A quick way to compare coverage is to take a list of products your users actually buy and count how many return usable calorie values. For products that still come up empty, let users enter the calories per 100 g from the label.

How Expotion's recipe calculator works

Look at the web calculator's calcResult function. It adds up the ingredient weights and calculates four recipe totals: calories, protein, fat, and carbohydrates. If you enter a serving weight, the function uses it. Otherwise, it divides the sum of ingredient weights by the number of servings and rounds the resulting weight.

The function uses the sum of ingredient weights to calculate both per-100 g and per-serving values. The serving weight field tells it how many grams are on the plate. The calculation has no separate input for the measured weight of the whole finished dish.

Here's what that means for the test case. Enter 100 g of dry grain at 360 kcal per 100 g and a serving weight of 150 g. The calculation gives 360 ร— 150 รท 100 = 540 kcal. To calculate from the finished dish, the model needs one more number, cookedWeight = 300. The serving fraction becomes 150 / 300, or 0.5, and the result is 180 kcal.

The function below shows how to pass the cooked weight separately. It calculates calories and keeps fractional values until display. The web calculator rounds the recipe's nutrition totals before scaling them to servings. Expotion web recipe calculator

3. Implement the calculation

The function takes three inputs: ingredients with weights and calories per 100 g, the cooked weight, and the serving weight. It returns calories for the whole recipe, per 100 g, and per serving. All weights are in grams.

function isPositiveNumber(value) {
  return Number.isFinite(value) && value > 0
}

function ingredientCalories(item) {
  if (
    !isPositiveNumber(item?.grams) ||
    !Number.isFinite(item?.kcalPer100g) ||
    item.kcalPer100g < 0
  ) {
    throw new Error('Invalid ingredient')
  }

  return (item.grams / 100) * item.kcalPer100g
}

export function calculateRecipe(ingredients, cookedWeight, portionWeight) {
  if (!Array.isArray(ingredients) || ingredients.length === 0) {
    throw new Error('Provide at least one ingredient')
  }
  if (!isPositiveNumber(cookedWeight)) {
    throw new Error('Cooked weight must be positive')
  }
  if (!isPositiveNumber(portionWeight) || portionWeight > cookedWeight) {
    throw new Error('Invalid portion weight')
  }

  let total = 0
  for (const ingredient of ingredients) {
    total += ingredientCalories(ingredient)
  }

  const per100g = total === 0 ? 0 : total * (100 / cookedWeight)
  const portion = total * (portionWeight / cookedWeight)
  if (![total, per100g, portion].every(Number.isFinite)) {
    throw new Error('Result is outside the numeric range')
  }

  return { total, per100g, portion }
}

Water with 0 kcal passes validation. A blank field, a string, and null fail. In the UI, check that the field is filled in before explicitly converting the input to a number. Number('') returns zero, so a blank can accidentally become 0 kcal. Number.isFinite() checks the type and whether the number is finite without coercing it. ECMAScript, Number.isFinite

4. Test where the calculation can break

Save the function as recipe.mjs and the tests as recipe.test.mjs, then run node --test recipe.test.mjs. The first test checks that the calculation uses the finished weight. The others cover a valid zero, invalid inputs, a serving larger than the dish, and premature rounding. Node.js test runner documentation

import { test } from 'node:test'
import assert from 'node:assert/strict'
import { calculateRecipe } from './recipe.mjs'

const grain = { grams: 100, kcalPer100g: 360 }

test('uses the cooked weight', () => {
  assert.deepEqual(calculateRecipe([grain], 300, 150), {
    total: 360, per100g: 120, portion: 180,
  })
})

test('accepts a real zero in the ingredient list', () => {
  const water = { grams: 200, kcalPer100g: 0 }
  assert.equal(calculateRecipe([grain, water], 300, 150).portion, 180)
})

test('rejects invalid numbers and portions', () => {
  for (const value of [null, '', '360', NaN, Infinity, -1]) {
    assert.throws(() => calculateRecipe(
      [{ grams: 100, kcalPer100g: value }], 300, 150,
    ), /Invalid ingredient/)
  }
  assert.throws(() => calculateRecipe([null], 300, 150))
  assert.throws(() => calculateRecipe([grain], 0, 50))
  assert.throws(() => calculateRecipe([grain], 300, 301))
})

test('keeps fractional calories through scaling', () => {
  const ingredient = { grams: 1, kcalPer100g: 25 }
  assert.equal(calculateRecipe([ingredient, ingredient], 2, 1).portion, 0.25)
})

What should the calculator show without a cooked weight?

Show the recipe total and ask the user to weigh the finished dish to get per-100 g and serving results. You can also offer an estimate based on the sum of the starting weights. If you do, say which weight the estimate uses. After boiling, baking, or draining, the difference can be substantial.

Store ingredients and cooked weight separately. If the user weighs the dish later, they can update a single value and recalculate the serving. See the Expotion recipe calculator for comparison.

Where the model loses accuracy

  • Cooking losses. If some oil stays in the pan, the finished weight alone can't tell you how many calories were left behind.

  • Uneven servings. If one person gets more meat and another gets more sauce, their servings can have different calorie counts even at the same weight.

  • Ingredient data. Check the food state and units. The formula will scale incorrect data just as readily as correct data.

  • Rounding. Two ingredients with 0.25 kcal each add up to 0.5 kcal. Round each to a whole number first and both become zero. Round when you display the result.

Sources

  1. Schakel et al., 1997. Procedures for Estimating Nutrient Values for Food Composition Databases

  2. Ecma International. Number.isFinite specification

  3. Node.js. Test runner documentation

  4. Open Food Facts API documentation

  5. Expotion Food API access

  6. fatsecret API editions and pricing

๐Ÿ“ฐ Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.