Created
October 19, 2023 11:16
-
-
Save matthewblewitt/35c5afebb1563a51fca0c24a663b7171 to your computer and use it in GitHub Desktop.
Excercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
Unreliable Webhook | |
There's a webhook that's calling webhookHandle that is unreliable. | |
It is possible that after it receives a paid status, it triggers a failed or paid one. | |
possible cases => | |
- pending → submitted → paid | |
- pending → submitted → failed | |
- pending → submitted → paid → paid | |
- pending → submitted → paid → failed | |
webhookHandler should only output the final status (paid or failed) once. | |
If webhookHandler gets paid and then failed, it should only show failed. | |
expected output: | |
log 1: pending | |
log 2: submitted | |
log 3: paid | |
OR | |
log 1: pending | |
log 2: submitted | |
log 3: failed | |
*/ | |
// code you can act on | |
let currentStatus = "pending"; | |
let statusComplete = false; | |
const webhookHandler = (status: string) => { | |
currentStatus = status; | |
if(statusComplete){ | |
return; | |
} | |
console.log(currentStatus) | |
if(currentStatus === 'paid' || currentStatus === 'failed'){ | |
statusComplete = true; | |
} | |
}; | |
// read only | |
// do not change the following code | |
const webhookTrigger = async () => { | |
webhookHandler("pending"); | |
await webhookSleep(); | |
webhookHandler("submitted"); | |
await webhookSleep(); | |
const isFailed1 = Math.round(Math.random()); | |
webhookHandler(isFailed1 ? "failed" : "paid"); | |
const shouldRepeatHandlerTrigger = Math.round(Math.random()); | |
if (shouldRepeatHandlerTrigger && !isFailed1) { | |
await webhookSleep(); | |
const isFailed2 = Math.round(Math.random()); | |
webhookHandler(isFailed2 ? "failed" : "paid"); | |
} | |
}; | |
const webhookSleep = () => { | |
const sleepTime = Math.floor(Math.random() * 1000); | |
return new Promise((r) => setTimeout(r, sleepTime)); | |
}; | |
webhookTrigger(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment