Design Cancellable Function — LeetCode 2650 Python Solution
HardJavaScript
- Problem
- #2650
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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 cancellable that accepts a generator object and returns an array of two values: a cancel function and a promise.
Example
function* tasks() {
const val = yield new Promise(resolve => resolve(2 + 2));
yield new Promise(resolve => setTimeout(resolve, 100));
return val + 1; // calculation shouldn't be done.
}
const [cancel, promise] = cancellable(tasks());
setTimeout(cancel, 50);
promise.catch(console.log); // logs "Cancelled" at t=50msComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) to O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 2650. Design Cancellable Function?
- LeetCode 2650. Design Cancellable Function is rated Hard on LeetCode.
- What topics does LeetCode 2650. Design Cancellable Function cover?
- LeetCode 2650. Design Cancellable Function is tagged JavaScript on LeetCode.