A nutrition calculator looks simple: add up some numbers. In practice you hit a few real problems. Food data is stored per 100 g but people eat 50 g or 200 g. Label calories don't quite match the macros. Net carbs depend on fibre. And a daily goal has to turn percentages into grams.
This post builds the core of one in plain JavaScript, with no libraries. I ran every example in Node before writing it down. The finished tool is here: free nutrition calculator .
Step 1: Scale per-100 g data to any amount
Most food tables give values per 100 g. To get any portion, multiply by grams / 100 :
const KCAL = { protein : 4 , carbs : 4 , fat : 9 } ;
function scale ( food , grams ) { if ( ! Number .…