mirror of
https://gitee.com/coder-xiaomo/leetcode-problemset
synced 2025-01-10 18:48:13 +08:00
72 lines
2.4 KiB
HTML
72 lines
2.4 KiB
HTML
<p>Given an asyncronous function <code>fn</code> and a time <code>t</code> in milliseconds, return a new <strong>time limited</strong> version of the input function.</p>
|
|
|
|
<p>A <strong>time limited</strong> function is a function that is identical to the original unless it takes longer than <code>t</code> milliseconds to fullfill. In that case, it will reject with <code>"Time Limit Exceeded"</code>. Note that it should reject with a string, not an <code>Error</code>.</p>
|
|
|
|
<p> </p>
|
|
<p><strong class="example">Example 1:</strong></p>
|
|
|
|
<pre>
|
|
<strong>Input:</strong>
|
|
fn = async (n) => {
|
|
await new Promise(res => setTimeout(res, 100));
|
|
return n * n;
|
|
}
|
|
inputs = [5]
|
|
t = 50
|
|
<strong>Output:</strong> {"rejected":"Time Limit Exceeded","time":50}
|
|
<strong>Explanation:</strong>
|
|
The 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.
|
|
</pre>
|
|
|
|
<p><strong class="example">Example 2:</strong></p>
|
|
|
|
<pre>
|
|
<strong>Input:</strong>
|
|
fn = async (n) => {
|
|
await new Promise(res => setTimeout(res, 100));
|
|
return n * n;
|
|
}
|
|
inputs = [5]
|
|
t = 150
|
|
<strong>Output:</strong> {"resolved":25,"time":100}
|
|
<strong>Explanation:</strong>
|
|
The function resolved 5 * 5 = 25 at t=100ms. The time limit is never reached.
|
|
</pre>
|
|
|
|
<p><strong class="example">Example 3:</strong></p>
|
|
|
|
<pre>
|
|
<strong>Input:</strong>
|
|
fn = async (a, b) => {
|
|
await new Promise(res => setTimeout(res, 120));
|
|
return a + b;
|
|
}
|
|
inputs = [5,10]
|
|
t = 150
|
|
<strong>Output:</strong> {"resolved":15,"time":120}
|
|
<strong>Explanation:</strong>
|
|
The function resolved 5 + 10 = 15 at t=120ms. The time limit is never reached.
|
|
</pre>
|
|
|
|
<p><strong class="example">Example 4:</strong></p>
|
|
|
|
<pre>
|
|
<strong>Input:</strong>
|
|
fn = async () => {
|
|
throw "Error";
|
|
}
|
|
inputs = []
|
|
t = 1000
|
|
<strong>Output:</strong> {"rejected":"Error","time":0}
|
|
<strong>Explanation:</strong>
|
|
The function immediately throws an error.</pre>
|
|
|
|
<p> </p>
|
|
<p><strong>Constraints:</strong></p>
|
|
|
|
<ul>
|
|
<li><code>0 <= inputs.length <= 10</code></li>
|
|
<li><code>0 <= t <= 1000</code></li>
|
|
<li><code>fn returns a promise</code></li>
|
|
</ul>
|