Created
February 3, 2024 00:23
-
-
Save GeKorm/043478bc74d3db29d9f3f3a8f4f69907 to your computer and use it in GitHub Desktop.
Cool problem
This file contains hidden or 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
| async function run(elements) { | |
| // ============ | |
| // your code here starts here | |
| // We will insert at arbitrary indices in order to preserve result order | |
| const results = Array.from({ length: TOTAL }); | |
| const requestPool = []; | |
| let processed = 0; | |
| for (const element of elements) { | |
| const poolSize = requestPool.length; | |
| if (poolSize >= MAX_INFLIGHT || processed >= TOTAL - MAX_INFLIGHT) { | |
| // When the request pool fills up, wait for the fastest response. It will be topped up immediately after. | |
| const [value, index] = await Promise.race(requestPool); | |
| results[index] = value; | |
| } | |
| const request = api(element).then((value) => { | |
| // Remove resolved promise from the pool | |
| requestPool.splice(requestPool.indexOf(request), 1); | |
| // We need a value and index to preserve call order | |
| return [value, elements.indexOf(element)]; | |
| }); | |
| requestPool.push(request); | |
| processed++; | |
| } | |
| // The first for .. of loop is done when all calls have been made, not when we get the responses | |
| // Here we wait for the last block of promises to settle and iterate the result | |
| // In a real-world program Promise.allSettled() may be preferable. Using Promise.all() for clarity | |
| for (const [value, index] of await Promise.all(requestPool)) { | |
| results[index] = value; | |
| } | |
| return results; | |
| // Real-world implementation would require error handling | |
| // your code ends here | |
| // ============ | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Full script is