Hands-On AI WorkshopHomeProjectsLearnResourcesPresenterHelpProgress

Project 22 of 30 · Pathway 6 — Everyday Automation

Smart Meal Planner and Grocery List

Shopping lists duplicate ingredients and omit quantities. Combine ingredient quantities by ingredient and unit.

Real-world benefit
Family meal planning and shared groceries.
Technologies
Google Sheets, Map, Composite keys
Required knowledge
None.
Time and level
About 15 minutes · Beginner
AI requirement
None: deterministic Apps Script
Expected baseline
Tomatoes 5 each; Lettuce 1 each

Loading the interactive studio…

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

Starter data: tab "Meals" (fictional)
DayMealIngredientQuantityUnit
MondayPastaTomatoes3each
TuesdaySaladTomatoes2each
TuesdaySaladLettuce1each

Setup in your own Google account

  1. Download 22-smart-meal-planner-and-grocery-list.zip (Code.gs, starter.csv, README).
  2. In Google Drive, create a lesson folder and a new Google Sheets file inside it.
  3. Rename the first tab to exactly Meals, then File → Import → Upload starter.csv → Replace current sheet.
  4. Extensions → Apps Script. Replace Code.gs with the downloaded file. Save.
  5. Reload the spreadsheet, choose Workshop → Run application and authorize when asked.
  6. 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

  1. Why is the key JSON.stringify([ingredient, unit])?

    1. It combines both parts safely so each ingredient-unit pair is grouped separately
    2. Maps require JSON
    3. 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.

  2. Is "Tomatoes 3 each + Tomatoes 200 g" combined?

    1. No, they stay on separate lines
    2. Yes, 203
    3. An error is thrown
    Answer

    No, they stay on separate lines Correct: incompatible units are never added.

  3. What does Array.from(m, ([k,v]) => …) do?

    1. Turns each Map entry into an output row
    2. Copies the Map
    3. Deletes the Map
    Answer

    Turns each Map entry into an output row Correct.

  4. Lettuce appears twice with units "each" and "head". Bug?

    1. Not a code bug: decide whether those units mean the same thing and normalize the data
    2. Yes, always merge
    3. 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.

  5. Would Gemini be useful here?

    1. Possibly for messy recipe text, but the aggregation should stay in code
    2. Yes, for adding numbers
    3. 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.

  1. 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.
  2. 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
  3. 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.
  4. 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.
  5. 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.

Related resources