{ "data": { "question": { "questionId": "2749", "questionFrontendId": "2637", "boundTopicId": null, "title": "Promise Time Limit", "titleSlug": "promise-time-limit", "content": "
Given an asynchronous function fn
and a time t
in milliseconds, return a new time limited version of the input function. fn
takes arguments provided to the time limited function.
The time limited function should follow these rules:
\n\nfn
completes within the time limit of t
milliseconds, the time limited function should resolve with the result.fn
exceeds the time limit, the time limited function should reject with the string "Time Limit Exceeded"
.\n
Example 1:
\n\n\nInput: \nfn = async (n) => { \n await new Promise(res => setTimeout(res, 100)); \n return n * n; \n}\ninputs = [5]\nt = 50\nOutput: {"rejected":"Time Limit Exceeded","time":50}\nExplanation:\nconst limited = timeLimit(fn, t)\nconst start = performance.now()\nlet result;\ntry {\n const res = await limited(...inputs)\n result = {"resolved": res, "time": Math.floor(performance.now() - start)};\n} catch (err) {\n result = {"rejected": err, "time": Math.floor(performance.now() - start)};\n}\nconsole.log(result) // Output\n\nThe provided function is set to resolve after 100ms. However, the time limit is set to 50ms. It rejects at t=50ms because the time limit was reached.\n\n\n
Example 2:
\n\n\nInput: \nfn = async (n) => { \n await new Promise(res => setTimeout(res, 100)); \n return n * n; \n}\ninputs = [5]\nt = 150\nOutput: {"resolved":25,"time":100}\nExplanation:\nThe function resolved 5 * 5 = 25 at t=100ms. The time limit is never reached.\n\n\n
Example 3:
\n\n\nInput: \nfn = async (a, b) => { \n await new Promise(res => setTimeout(res, 120)); \n return a + b; \n}\ninputs = [5,10]\nt = 150\nOutput: {"resolved":15,"time":120}\nExplanation:\nThe function resolved 5 + 10 = 15 at t=120ms. The time limit is never reached.\n\n\n
Example 4:
\n\n\nInput: \nfn = async () => { \n throw "Error";\n}\ninputs = []\nt = 1000\nOutput: {"rejected":"Error","time":0}\nExplanation:\nThe function immediately throws an error.\n\n
\n
Constraints:
\n\n0 <= inputs.length <= 10
0 <= t <= 1000
fn
returns a promiseNode.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES6 features.
lodash.js library is included by default.
\\r\\n\\r\\nFor Priority Queue / Queue data structures, you may use 5.3.0 version of datastructures-js/priority-queue and 4.2.1 version of datastructures-js/queue.
\"], \"typescript\": [\"Typescript\", \"TypeScript 5.1.6, Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES2022 features.
lodash.js library is included by default.
\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }