{ "data": { "question": { "questionId": "2821", "questionFrontendId": "2715", "boundTopicId": null, "title": "Execute Cancellable Function With Delay", "titleSlug": "execute-cancellable-function-with-delay", "content": "
Given a function fn
, an array or arguments args
, and a timeout t
in milliseconds, return a cancel function cancelFn
.
After a delay of t
, fn
should be called with args
passed as parameters unless cancelFn
was called first. In that case, fn
should never be called.
\n
Example 1:
\n\n\nInput: fn = (x) => x * 5, args = [2], t = 20, cancelTime = 50\nOutput: [{"time": 20, "returned": 10}]\nExplanation: \nconst cancel = cancellable(fn, [2], 20); // fn(2) called at t=20ms\nsetTimeout(cancel, 50);\n\nthe cancelTime (50ms) is after the delay time (20ms), so fn(2) should be called at t=20ms. The value returned from fn is 10.\n\n\n
Example 2:
\n\n\nInput: fn = (x) => x**2, args = [2], t = 100, cancelTime = 50\nOutput: []\nExplanation: fn(2) was never called because cancelTime (50ms) is before the delay time (100ms).\n\n\n
Example 3:
\n\n\nInput: fn = (x1, x2) => x1 * x2, args = [2,4], t = 30, cancelTime = 100\nOutput: [{"time": 30, "returned": 8}]\nExplanation: fn(2, 4) was called at t=30ms because cancelTime > t.\n\n\n
\n
Constraints:
\n\nfn is a function
args is a valid JSON array
1 <= args.length <= 10
20 <= t <= 1000
10 <= cancelT <= 1000
Node.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 4.5.4, Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES2020 features.
lodash.js library is included by default.
\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }