satyacode
Background
Back to js-loops

05-sabzi-mandi.js

JavaScript
1/**
2 * 🥬 Amma ki Sabzi Mandi Shopping
3 *
4 * Amma subah subah sabzi mandi gayi hain. Unke paas ek shopping list hai
5 * (kaunsi sabzi, kitne kg) aur mandi mein har sabzi ka rate alag hai.
6 * Amma smart hain - agar koi sabzi Rs 80/kg se zyada hai, toh nahi leni!
7 *
8 * Rules (use for...of loop):
9 *   - shoppingList is an array of objects: [{ name: "aloo", qty: 2 }, ...]
10 *   - priceList is an object: { aloo: 30, tamatar: 40, ... }
11 *   - Loop through each item in shoppingList using for...of
12 *   - Skip the item if:
13 *     (a) sabzi ka naam priceList mein nahi hai (not available in mandi)
14 *     (b) price per kg > Rs 80 (too expensive, Amma says "bahut mehenga hai!")
15 *   - For valid items, add to bill and build items array
16 *
17 * @param {Array<{name: string, qty: number}>} shoppingList - Amma ki list
18 * @param {Object<string, number>} priceList - Mandi ke rates (per kg)
19 * @returns {{ items: Array<{name: string, qty: number, cost: number}>, totalBill: number }}
20 *
21 * @example
22 *   sabziMandiBill(
23 *     [{ name: "aloo", qty: 2 }, { name: "shimla mirch", qty: 1 }],
24 *     { aloo: 30, tamatar: 40, shimla_mirch: 90 }
25 *   )
26 *   // shimla mirch not in priceList (key mismatch), shimla_mirch > 80
27 *   // => { items: [{ name: "aloo", qty: 2, cost: 60 }], totalBill: 60 }
28 *
29 *   sabziMandiBill([], { aloo: 30 })
30 *   // => { items: [], totalBill: 0 }
31 */
32export function sabziMandiBill(shoppingList, priceList) {
33  let items =[];
34  let totalBill = 0;
35  
36  for(const item of shoppingList){
37    const itemName = item.name;
38    const quantity = item.qty;
39    const price = priceList[itemName]
40
41    if(price === undefined){
42      continue;
43    }
44
45    if(price > 80){
46      continue;
47    }
48
49    const cost = price * quantity;
50
51    items.push({
52      name: itemName,
53      qty: quantity,
54      cost
55    });
56
57    totalBill = totalBill + cost
58  }
59  return {items, totalBill}
60}
61