satyacode
Background
Back to js-loops

09-upi-retry.js

JavaScript
1/**
2 * 💸 Bunty ka UPI Payment Retry
3 *
4 * Bunty apne dost ko paise bhej raha hai UPI se, lekin network thoda
5 * flaky hai. Payment kabhi success hota hai, kabhi fail. Bunty ka app
6 * automatically retry karta hai with exponential backoff.
7 *
8 * Rules (use do...while loop):
9 *   - outcomes is an array of strings: "success" or "fail"
10 *   - ALWAYS attempt at least once (that's why do...while!)
11 *   - outcomes[0] is the result of attempt 1, outcomes[1] is attempt 2, etc.
12 *   - If the attempt is "success", stop immediately
13 *   - If the attempt is "fail", add wait time and try again
14 *   - Wait times follow exponential backoff: 1s, 2s, 4s, 8s
15 *     (wait time is added AFTER a failed attempt, before next retry)
16 *   - Maximum 5 attempts total (if all fail, stop after 5th)
17 *   - totalWaitTime = sum of all wait times between attempts
18 *
19 * Validation:
20 *   - Agar outcomes array nahi hai ya empty hai,
21 *     return: { attempts: 0, success: false, totalWaitTime: 0 }
22 *
23 * @param {string[]} outcomes - Array of "success" or "fail" for each attempt
24 * @returns {{ attempts: number, success: boolean, totalWaitTime: number }}
25 *
26 * @example
27 *   upiRetry(["fail", "fail", "success"])
28 *   // Attempt 1: fail, wait 1s
29 *   // Attempt 2: fail, wait 2s
30 *   // Attempt 3: success!
31 *   // => { attempts: 3, success: true, totalWaitTime: 3 }
32 *
33 *   upiRetry(["fail", "fail", "fail", "fail", "fail", "fail"])
34 *   // 5 attempts all fail, wait: 1+2+4+8 = 15s (no wait after last)
35 *   // => { attempts: 5, success: false, totalWaitTime: 15 }
36 */
37export function upiRetry(outcomes) {
38  if(!Array.isArray(outcomes) ||outcomes.length === 0){
39    return { attempts: 0, success: false, totalWaitTime: 0 }
40  }
41  let attempts = 0
42  let totalWaitTime = 0
43  let success = false
44  let waitTime = 1
45  do {
46    attempts ++
47    if(outcomes[attempts - 1] === "success"){
48       success = true
49    }
50    if(outcomes[attempts - 1] === "fail" && attempts < 5){
51       totalWaitTime = totalWaitTime + waitTime
52       waitTime *= 2
53    }
54    
55  } while (attempts < 5 && !success);
56
57  return { attempts, success, totalWaitTime }
58}
59