1
0
mirror of https://gitee.com/coder-xiaomo/leetcode-problemset synced 2025-01-11 02:58:13 +08:00
Code Issues Projects Releases Wiki Activity GitHub Gitee
leetcode-problemset/leetcode/originData/design-cancellable-function.json

60 lines
12 KiB
JSON
Raw Normal View History

2023-04-23 22:41:08 +08:00
{
"data": {
"question": {
"questionId": "2788",
"questionFrontendId": "2650",
"boundTopicId": null,
"title": "Design Cancellable Function",
"titleSlug": "design-cancellable-function",
2023-12-09 18:42:21 +08:00
"content": "<p>Sometimes you have a long running task, and you may wish to cancel it before it completes. To help with this goal, write a function&nbsp;<code>cancellable</code> that accepts a generator object and returns an array of two values: a <strong>cancel function</strong> and a <strong>promise</strong>.</p>\n\n<p>You may assume the generator function will only&nbsp;yield promises. It is your function&#39;s responsibility to pass the values resolved by the promise back to the generator. If the promise rejects, your function should throw that&nbsp;error back to the generator.</p>\n\n<p>If the cancel callback is called before the generator is done, your function should throw an error back to the generator. That error should be the string&nbsp;<code>&quot;Cancelled&quot;</code>&nbsp;(Not an <code>Error</code>&nbsp;object). If the error was caught, the returned&nbsp;promise should resolve with the next value that was yielded or returned. Otherwise, the promise should reject with the thrown error. No more code should be executed.</p>\n\n<p>When the generator is done, the promise your function returned should resolve the value the generator returned. If, however, the generator throws an error, the returned promise should reject with the error.</p>\n\n<p>An example of how your code would be used:</p>\n\n<pre>\nfunction* tasks() {\n const val = yield new Promise(resolve =&gt; resolve(2 + 2));\n yield new Promise(resolve =&gt; setTimeout(resolve, 100));\n return val + 1; // calculation shouldn&#39;t be done.\n}\nconst [cancel, promise] = cancellable(tasks());\nsetTimeout(cancel, 50);\npromise.catch(console.log); // logs &quot;Cancelled&quot; at t=50ms\n</pre>\n\n<p>If&nbsp;instead&nbsp;<code>cancel()</code> was not called or was called after <code>t=100ms</code>, the promise would&nbsp;have resolved&nbsp;<code>5</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \ngeneratorFunction = function*() { \n&nbsp; return 42; \n}\ncancelledAt = 100\n<strong>Output:</strong> {&quot;resolved&quot;: 42}\n<strong>Explanation:</strong>\nconst generator = generatorFunction();\nconst [cancel, promise] = cancellable(generator);\nsetTimeout(cancel, 100);\npromise.then(console.log); // resolves 42 at t=0ms\n\nThe generator immediately yields 42 and finishes. Because of that, the returned promise immediately resolves 42. Note that cancelling a finished generator does nothing.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong>\ngeneratorFunction = function*() { \n&nbsp; const msg = yield new Promise(res =&gt; res(&quot;Hello&quot;)); \n&nbsp; throw `Error: ${msg}`; \n}\ncancelledAt = null\n<strong>Output:</strong> {&quot;rejected&quot;: &quot;Error: Hello&quot;}\n<strong>Explanation:</strong>\nA promise is yielded. The function handles this by waiting for it to resolve and then passes the resolved value back to the generator. Then an error is thrown which has the effect of causing the promise to reject with the same thrown error.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> \ngeneratorFunction = function*() { \n&nbsp; yield new Promise(res =&gt; setTimeout(res, 200)); \n&nbsp; return &quot;Success&quot;; \n}\ncancelledAt = 100\n<strong>Output:</strong> {&quot;rejected&quot;: &quot;Cancelled&quot;}\n<strong>Explanation:</strong>\nWhile the function is waiting for the yielded promise to resolve, cancel() is called. This causes an error message to be sent back to the generator. Since this error is uncaught, the returned promise rejected with this error.\n</pre>\n\n<p><strong class=\"example\">Example 4:</strong></p>\n\n<pre>\n<strong>Input:</strong>\ngeneratorFunction = function*() { \n&nbsp; let result = 0; \n&nbsp; yield new Promise(res =&gt; setTimeout(res, 100));\n&nbsp; result += yield new Promise(res =&gt; res(1)); \n&nbsp; yield new Promise(res =&gt; setTimeout(res, 100)); \n&nbsp; result += yield new Promise(res =&gt; res(1)); \n&nbsp; return result;\n}\ncancel
2023-04-23 22:41:08 +08:00
"translatedTitle": null,
"translatedContent": null,
"isPaidOnly": false,
"difficulty": "Hard",
2023-12-09 19:57:46 +08:00
"likes": 59,
2023-12-09 18:42:21 +08:00
"dislikes": 13,
2023-04-23 22:41:08 +08:00
"isLiked": null,
"similarQuestions": "[{\"title\": \"Generate Fibonacci Sequence\", \"titleSlug\": \"generate-fibonacci-sequence\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Nested Array Generator\", \"titleSlug\": \"nested-array-generator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
"exampleTestcases": "function*() { return 42; }\n{\"cancelledAt\":100}\nfunction*() { const msg = yield new Promise(res => res(\"Hello\")); throw `Error: ${msg}`; }\n{\"cancelledAt\":null}\nfunction*() { yield new Promise(res => setTimeout(res, 200)); return \"Success\"; }\n{\"cancelledAt\":100}\nfunction*() { let result = 0; yield new Promise(res => setTimeout(res, 100)); result += yield new Promise(res => res(1)); yield new Promise(res => setTimeout(res, 100)); result += yield new Promise(res => res(1)); return result; }\n{\"cancelledAt\":null}\nfunction*() { let result = 0; try { yield new Promise(res => setTimeout(res, 100)); result += yield new Promise(res => res(1)); yield new Promise(res => setTimeout(res, 100)); result += yield new Promise(res => res(1)); } catch(e) { return result; } return result; }\n{\"cancelledAt\":150}\nfunction*() { try { yield new Promise((resolve, reject) => reject(\"Promise Rejected\")); } catch(e) { let a = yield new Promise(resolve => resolve(2)); let b = yield new Promise(resolve => resolve(2)); return a + b; }; }\n{\"cancelledAt\":null}",
"categoryTitle": "JavaScript",
"contributors": [],
"topicTags": [],
"companyTagStats": null,
"codeSnippets": [
{
"lang": "JavaScript",
"langSlug": "javascript",
"code": "/**\n * @param {Generator} generator\n * @return {[Function, Promise]}\n */\nvar cancellable = function(generator) {\n \n};\n\n/**\n * function* tasks() {\n * const val = yield new Promise(resolve => resolve(2 + 2));\n * yield new Promise(resolve => setTimeout(resolve, 100));\n * return val + 1;\n * }\n * const [cancel, promise] = cancellable(tasks());\n * setTimeout(cancel, 50);\n * promise.catch(console.log); // logs \"Cancelled\" at t=50ms\n */",
"__typename": "CodeSnippetNode"
},
{
"lang": "TypeScript",
"langSlug": "typescript",
2023-12-09 18:42:21 +08:00
"code": "function cancellable<T>(generator: Generator<Promise<any>, T, unknown>): [() => void, Promise<T>] {\n\t\n};\n\n/**\n * function* tasks() {\n * const val = yield new Promise(resolve => resolve(2 + 2));\n * yield new Promise(resolve => setTimeout(resolve, 100));\n * return val + 1;\n * }\n * const [cancel, promise] = cancellable(tasks());\n * setTimeout(cancel, 50);\n * promise.catch(console.log); // logs \"Cancelled\" at t=50ms\n */",
2023-04-23 22:41:08 +08:00
"__typename": "CodeSnippetNode"
}
],
2023-12-09 19:57:46 +08:00
"stats": "{\"totalAccepted\": \"1.4K\", \"totalSubmission\": \"2.7K\", \"totalAcceptedRaw\": 1360, \"totalSubmissionRaw\": 2671, \"acRate\": \"50.9%\"}",
2023-04-23 22:41:08 +08:00
"hints": [
"This question tests understanding of two-way communication between generator functions and the code that evaluates the generator. It is a powerful technique which is used in libraries such as redux-saga.",
"You can pass a value value to a generator function X by calling generator.next(X). Then in the generator function, you can access this value by calling let X = yield \"val to pass into generator.next()\";",
"You can throw an error back to a generator function by calling generator.throw(err). If this error isn't caught in the generator function, that will throw an error."
],
"solution": null,
"status": null,
"sampleTestCase": "function*() { return 42; }\n{\"cancelledAt\":100}",
"metaData": "{\n \"name\": \"cancellable\",\n \"params\": [\n {\n \"name\": \"generator\",\n \"type\": \"string\"\n },\n {\n \"type\": \"integer\",\n \"name\": \"cancelledAT\"\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,
2023-12-09 18:42:21 +08:00
"envInfo": "{\"javascript\": [\"JavaScript\", \"<p><code>Node.js 16.13.2</code>.</p>\\r\\n\\r\\n<p>Your code is run with <code>--harmony</code> flag, enabling <a href=\\\"http://node.green/\\\" target=\\\"_blank\\\">new ES6 features</a>.</p>\\r\\n\\r\\n<p><a href=\\\"https://lodash.com\\\" target=\\\"_blank\\\">lodash.js</a> library is included by default.</p>\\r\\n\\r\\n<p>For Priority Queue / Queue data structures, you may use 5.3.0 version of <a href=\\\"https://github.com/datastructures-js/priority-queue/tree/fb4fdb984834421279aeb081df7af624d17c2a03\\\" target=\\\"_blank\\\">datastructures-js/priority-queue</a> and 4.2.1 version of <a href=\\\"https://github.com/datastructures-js/queue/tree/e63563025a5a805aa16928cb53bcd517bfea9230\\\" target=\\\"_blank\\\">datastructures-js/queue</a>.</p>\"], \"typescript\": [\"Typescript\", \"<p><code>TypeScript 5.1.6, Node.js 16.13.2</code>.</p>\\r\\n\\r\\n<p>Your code is run with <code>--harmony</code> flag, enabling <a href=\\\"http://node.green/\\\" target=\\\"_blank\\\">new ES2022 features</a>.</p>\\r\\n\\r\\n<p><a href=\\\"https://lodash.com\\\" target=\\\"_blank\\\">lodash.js</a> library is included by default.</p>\"]}",
2023-04-23 22:41:08 +08:00
"libraryUrl": null,
"adminUrl": null,
"challengeQuestion": null,
"__typename": "QuestionNode"
}
}
}