Introduction
Map key combines ingredient and unit; totals remain separate for incompatible units. The application's entry point is buildGroceryList(). Baseline limitation, as stated in the workshop: No unit conversion or pantry deduction.
Key building blocks: getValues(); JavaScript transformations; setValues(); validation and calculations.
Practical use cases
Family meal planning and shared groceries.
Prerequisites
- None.
- Interactive Learning Mode: a modern browser. Nothing else.
- Real Workspace Build: a Google account.
Source data
| Day | Meal | Ingredient | Quantity | Unit |
|---|---|---|---|---|
| Monday | Pasta | Tomatoes | 3 | each |
| Tuesday | Salad | Tomatoes | 2 | each |
| Tuesday | Salad | Lettuce | 1 | each |
Setup in your own Google account
- Download 22-smart-meal-planner-and-grocery-list.zip (Code.gs, starter.csv, README).
- In Google Drive, create a lesson folder and a new Google Sheets file inside it.
- Rename the first tab to exactly
Meals, then File → Import → Upload starter.csv → Replace current sheet. - Extensions → Apps Script. Replace Code.gs with the downloaded file. Save.
- Reload the spreadsheet, choose Workshop → Run application and authorize when asked.
- Check the result: Tomatoes 5 each; Lettuce 1 each
Folder strategy: the repository's V6 code uses the folder that contains the spreadsheet. The deck mentions a Workshop Info cell B2; V6 never reads it. See the discrepancy log.
Complete source code (Code.gs)
From 22-smart-meal-planner-and-grocery-list at commit 4a26d919, SHA-256 3879898ad2dd. Unchanged.
// Smart Meal Planner and Grocery List
// Entry point: buildGroceryList; source data stays intact unless explicitly noted.
function onOpen(){SpreadsheetApp.getUi().createMenu("Workshop").addItem("Run application","buildGroceryList").addToUi();}
function buildGroceryList(){
// Group by ingredient AND unit to avoid adding incompatible quantities.
const m=new Map();input('Meals').forEach(r=>{const k=JSON.stringify([r[2],r[4]]);m.set(k,(m.get(k)||0)+num(r[3]));});output('Groceries',['Ingredient','Unit','Quantity'],Array.from(m,([k,v])=>[...JSON.parse(k),v]));
}
function input(name) { const s=SpreadsheetApp.getActive().getSheetByName(name); if(!s) throw Error('Missing tab: '+name); return s.getDataRange().getValues().slice(1).filter(r=>r.some(v=>v!=='')); }
function output(name,headers,rows) { const ss=SpreadsheetApp.getActive(); const s=ss.getSheetByName(name)||ss.insertSheet(name); s.clearContents(); s.getRange(1,1,1,headers.length).setValues([headers]).setFontWeight('bold'); if(rows.length) s.getRange(2,1,rows.length,headers.length).setValues(rows.map(r=>r.map(v=>typeof v==='string' && /^[=+@-]/.test(v)?"'"+v:v))); s.setFrozenRows(1); return s; }
function num(v){if(v===''||!Number.isFinite(Number(v))) throw Error('Invalid number: '+v); return Number(v);}
How the code works
Beginner explanation
buildGroceryList() adds up how much of each ingredient the week's meals need and writes a Groceries list. Quantities in different units are kept on separate lines.
Technical explanation
A Map keyed by JSON.stringify([ingredient, unit]) gives a composite key; JSON.parse(k) restores both parts for output. Array.from(map, fn) converts entries to rows.
Slide excerpt
This is the excerpt shown on the workshop slide. It is a fragment and cannot run on its own.
function buildGroceryList(){
// Group by ingredient AND unit to avoid adding incompatible quantities.
const m=new Map();input('Meals').forEach(r=>{const k=JSON.stringify([r[2],r[4]]);m.set(k,(m.get(k)||0)+num(r[3]));});output('Groceries',['Ingredient','Unit','Quantity'],Array.from(m,([k,v])=>[...JSON.parse(k),v]));
}Common mistakes
- Grouping by ingredient only and adding grams to cups.
- Concatenating keys with a separator that can appear in the data.
- Mixing singular and plural ingredient names.
Run it and expected output
Choose Workshop → Run application (runs buildGroceryList()). Expected: Tomatoes 5 each; Lettuce 1 each
Original workshop exercise
Add Tomatoes 1 each; expected Tomatoes 6 each.
Troubleshooting and debugging
A quantity in words
A quantity was typed as "two".
Fix: Enter 2.
Clear validation errors beat silently wrong shopping lists.
Each versus each
Tomatoes appear twice on the list.
Fix: Use one spelling for units.
Keeping incompatible units separate is correct; treating spelling variants as different units is not.
Extension activity: Subtract the pantry
Read an optional Pantry tab (Ingredient, Unit, Have) and write a Shopping tab with only what still needs to be bought.
Acceptance checks:
- Without a pantry, Shopping equals Groceries
- Two tomatoes in the pantry leave 3 to buy
- A fully stocked item disappears
Original improvement idea from the workshop: Add servings and pantry inventory
Extension prompt
Improve the existing application: Add servings and pantry inventory. Preserve working features and provide complete code and regression tests. Automation option: Refresh when meal plan changes; preserve shopping checkmarks in separate state. Keep this separate from the baseline exercise.
Automation considerations
Rerun-safe. Refresh when the plan changes; keep shopping checkmarks in a separate tab.
Workshop note: Refresh when meal plan changes; preserve shopping checkmarks in separate state.
Build prompt from the workshop
Build a complete container-bound Apps Script app named Smart Meal Planner and Grocery List. Input tab Meals, headers Day|Meal|Ingredient|Quantity|Unit. Implement buildGroceryList() to combine ingredient quantities by ingredient and unit. Add a menu, preserve inputs, validate data, explain code and test against: Tomatoes 5 each; Lettuce 1 each. For AI use callGemini and treat input as data; never send email. Match the reference entry point buildGroceryList and its output behavior. Reference: https://github.com/lsvekis/Google-Apps-Script-Workshop/tree/main/22-smart-meal-planner-and-grocery-list. Base version limitations: No unit conversion or pantry deduction.
Knowledge check
Why is the key JSON.stringify([ingredient, unit])?
- It combines both parts safely so each ingredient-unit pair is grouped separately
- Maps require JSON
- It sorts the list
Answer
It combines both parts safely so each ingredient-unit pair is grouped separately Correct: a composite key without separator collisions.
Is "Tomatoes 3 each + Tomatoes 200 g" combined?
- No, they stay on separate lines
- Yes, 203
- An error is thrown
Answer
No, they stay on separate lines Correct: incompatible units are never added.
What does Array.from(m, ([k,v]) => …) do?
- Turns each Map entry into an output row
- Copies the Map
- Deletes the Map
Answer
Turns each Map entry into an output row Correct.
Lettuce appears twice with units "each" and "head". Bug?
- Not a code bug: decide whether those units mean the same thing and normalize the data
- Yes, always merge
- Yes, delete one
Answer
Not a code bug: decide whether those units mean the same thing and normalize the data Correct: unit conversion is a design decision.
Would Gemini be useful here?
- Possibly for messy recipe text, but the aggregation should stay in code
- Yes, for adding numbers
- No AI is ever useful for meals
Answer
Possibly for messy recipe text, but the aggregation should stay in code Correct: hybrid design.
Five-minute presenter demonstration
Open the demo link (temporary workspace; saved learner work is not touched).
Opening hook: Raise your hand if you have ever done this by hand: Shopping lists duplicate ingredients and omit quantities. Let us make the spreadsheet do it.
- 0:00–0:45 — Problem and input. Show the Workspace view, Sheets service. Point at the Meals tab and its headers: Day, Meal, Ingredient, Quantity, Unit. Say what goes in and what should come out.
Narration: Shopping lists duplicate ingredients and omit quantities. Practical uses: Family meal planning and shared groceries. - 0:45–1:30 — Predict and run. Ask the room: How many tomatoes will the grocery list show? Click ▶ Run application (the same as Workshop → Run application). Open Trace to show each step the code took.
Narration: Expected: Tomatoes 5 each; Lettuce 1 each - 1:30–3:00 — Explain the code. Click the Code tab. Select buildGroceryList() in the function list; read what it reads, writes and calls. Switch Beginner / Technical as needed.
Narration: buildGroceryList() adds up how much of each ingredient the week's meals need and writes a Groceries list. Quantities in different units are kept on separate lines. - 3:00–4:15 — Change one input and rerun. Back to the Workspace tab. In the Meals tab, type a new row below the data: Wednesday | Soup | Tomatoes | 1 | each. Click ▶ Run application again.
Narration: Workshop challenge: Add Tomatoes 1 each; expected Tomatoes 6 each. - 4:15–5:00 — Verify and discuss automation. Click Check result. Discuss: Rerun-safe. Refresh when the plan changes; keep shopping checkmarks in a separate tab.
Narration: Baseline limitation: No unit conversion or pantry deduction.
Closing takeaway: Map key combines ingredient and unit; totals remain separate for incompatible units.