Write a TypeScript function named createIdempotencyGuard.
Requirements:
- It accepts an object with
key, ttlMs, and an async handler function.
- If the same key is currently being processed, return the same in-flight Promise instead of running handler again.
- After successful completion, cache and return the result until ttlMs expires.
- If handler throws, do not cache the failure; a future call with the same key must retry.
- Use only in-memory JavaScript/TypeScript primitives; no libraries.
- Explain time and space complexity.
- Include at least 5 test cases covering concurrency, caching, expiry, and errors.
Output format:
{
"code": "...",
"explanation": "...",
"complexity": {
"time": "...",
"space": "..."
},
"tests": ["...", "...", "...", "...", "..."]
}