{ "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.

\n\n

The time limited function should follow these rules:

\n\n\n\n

 

\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:\n​​​​The 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\n\n", "translatedTitle": null, "translatedContent": null, "isPaidOnly": false, "difficulty": "Medium", "likes": 405, "dislikes": 51, "isLiked": null, "similarQuestions": "[{\"title\": \"Sleep\", \"titleSlug\": \"sleep\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Debounce\", \"titleSlug\": \"debounce\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Promise Pool\", \"titleSlug\": \"promise-pool\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Cache With Time Limit\", \"titleSlug\": \"cache-with-time-limit\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Throttle\", \"titleSlug\": \"throttle\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "exampleTestcases": "async (n) => { await new Promise(res => setTimeout(res, 100)); return n * n; }\n[5]\n50\nasync (n) => { await new Promise(res => setTimeout(res, 100)); return n * n; }\n[5]\n150\nasync (a, b) => { await new Promise(res => setTimeout(res, 120)); return a + b; }\n[5,10]\n150\nasync () => { throw \"Error\"; }\n[]\n1000", "categoryTitle": "JavaScript", "contributors": [], "topicTags": [], "companyTagStats": null, "codeSnippets": [ { "lang": "JavaScript", "langSlug": "javascript", "code": "/**\n * @param {Function} fn\n * @param {number} t\n * @return {Function}\n */\nvar timeLimit = function(fn, t) {\n \n\treturn async function(...args) {\n \n }\n};\n\n/**\n * const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);\n * limited(150).catch(console.log) // \"Time Limit Exceeded\" at t=100ms\n */", "__typename": "CodeSnippetNode" }, { "lang": "TypeScript", "langSlug": "typescript", "code": "type Fn = (...params: any[]) => Promise;\n\nfunction timeLimit(fn: Fn, t: number): Fn {\n \n\treturn async function(...args) {\n \n }\n};\n\n/**\n * const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);\n * limited(150).catch(console.log) // \"Time Limit Exceeded\" at t=100ms\n */", "__typename": "CodeSnippetNode" } ], "stats": "{\"totalAccepted\": \"30.3K\", \"totalSubmission\": \"37.3K\", \"totalAcceptedRaw\": 30329, \"totalSubmissionRaw\": 37334, \"acRate\": \"81.2%\"}", "hints": [ "You can return a copy of a function with: \r\n\r\nfunction outerFunction(fn) { \r\n return function innerFunction(...params) {\r\n return fn(...params);\r\n };\r\n}", "Inside the inner function, you will need to return a new Promise.", "You can create a new promise like: new Promise((resolve, reject) => {}).", "You can execute code with a delay with \"setTimeout(fn, delay)\"", "To reject a promise after a delay, \"setTimeout(() => reject('err'), delay)\"", "You can resolve and reject when the passed promise resolves or rejects with: \"fn(...params).then(resolve).catch(reject)\"" ], "solution": { "id": "1899", "canSeeDetail": false, "paidOnly": true, "hasVideoSolution": false, "paidOnlyVideo": true, "__typename": "ArticleNode" }, "status": null, "sampleTestCase": "async (n) => { await new Promise(res => setTimeout(res, 100)); return n * n; }\n[5]\n50", "metaData": "{\n \"name\": \"timeLimit\",\n \"params\": [\n {\n \"name\": \"fn\",\n \"type\": \"string\"\n },\n {\n \"type\": \"string\",\n \"name\": \"inputs\"\n },\n {\n \"type\": \"integer\",\n \"name\": \"t\"\n }\n ],\n \"return\": {\n \"type\": \"string\"\n },\n \"languages\": [\n \"javascript\",\n \"typescript\"\n ],\n \"manual\": true\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "enableTestMode": false, "enableDebugger": false, "envInfo": "{\"javascript\": [\"JavaScript\", \"

Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES6 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\\r\\n\\r\\n

For 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.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES2022 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }