Back to js-loops
06-diwali-lights.js
JavaScript
1/**
2 * 🪔 Sharma ji ki Diwali Decoration
3 *
4 * Sharma ji apne ghar ko Diwali pe sajana chahte hain light strings se.
5 * Unke paas ek budget hai aur market mein alag alag colors ki light strings
6 * hain different lengths mein. Sharma ji sab kuch lena chahte hain, lekin
7 * budget se zyada nahi!
8 *
9 * Color rates (per meter):
10 * - "golden" = Rs 50/meter
11 * - "multicolor" = Rs 40/meter
12 * - "white" = Rs 30/meter
13 * - Any other color = Rs 35/meter
14 *
15 * Rules:
16 * Step 1 - Use for...of to loop through lightStrings and add ALL of them
17 * to selected list with their cost calculated
18 * Step 2 - Use a while loop to check: agar totalCost > budget, toh remove
19 * the LAST item from selected, subtract its cost, and keep removing until
20 * totalCost <= budget
21 *
22 * @param {Array<{color: string, length: number}>} lightStrings - Available light strings
23 * @param {number} budget - Sharma ji ka budget in rupees
24 * @returns {{ selected: Array<{color: string, length: number, cost: number}>, totalLength: number, totalCost: number }}
25 *
26 * Validation:
27 * - Agar lightStrings array nahi hai ya budget positive number nahi hai,
28 * return: { selected: [], totalLength: 0, totalCost: 0 }
29 *
30 * @example
31 * diwaliLightsPlan(
32 * [{ color: "golden", length: 5 }, { color: "white", length: 10 }, { color: "multicolor", length: 3 }],
33 * 400
34 * )
35 *
36 * golden: 5*50=250, white: 10*30=300, multicolor: 3*40=120
37 * Total = 670 > 400, remove multicolor (670-120=550), still > 400,
38 * remove white (550-300=250), 250 <= 400
39 * => { selected: [{ color: "golden", length: 5, cost: 250 }], totalLength: 5, totalCost: 250 }
40 */
41export function diwaliLightsPlan(lightStrings, budget) {
42 if(!Array.isArray(lightStrings) || budget < 0 || typeof budget !== "number"){
43 return {selected: [], totalLength: 0, totalCost: 0 }
44 }
45
46 let selected = [];
47 let totalCost = 0;
48 let totalLength = 0;
49
50 function getRateByColor(color){
51 switch(color) {
52 case "golden": return 50;
53 case "multicolor": return 40;
54 case "white": return 30;
55 default: return 35;
56 }
57 }
58
59 for(const item of lightStrings){
60 const rate = getRateByColor(item.color)
61
62 const cost = rate*item.length
63
64 selected.push({
65 color:item.color,
66 length: item.length,
67 cost
68 })
69
70 totalCost += cost
71 totalLength += item.length
72 }
73
74 while(totalCost > budget && selected.length > 0){
75 const removedItem = selected.pop()
76 totalCost -= removedItem.cost;
77 totalLength -= removedItem.length
78 }
79 return {
80 selected, totalLength, totalCost
81 }
82}
83