Time-Limited Promises Lab

Easy
12
38.5% Acceptance

Create a lab to implement time-limited asynchronous functions, which allows you to set a time limit in milliseconds for the given asynchronous function to be executed. If the function takes more time than the specified time limit, it should be rejected with the string "Time Limit Exceeded".

Lab Description

In this lab, you will be implementing a function called timeLimit, which will take an asynchronous function fn and a time t in milliseconds, and return a new time-limited version of the input function.

A time-limited function is a function that will behave identically to the original function, unless it takes longer than t milliseconds to fulfill. If it exceeds the time limit, the function should reject with the string "Time Limit Exceeded".

Examples:

Example 1:

const timeLimitedFn = timeLimit(async (n) => { await new Promise((res) => setTimeout(res, 100)); return n * n; }, 50); timeLimitedFn(5) .then((result) => console.log(result)) .catch((err) => console.log(err)); // Output: "Time Limit Exceeded"

Example 2:

const timeLimitedFn = timeLimit(async (n) => { await new Promise((res) => setTimeout(res, 100)); return n * n; }, 150); timeLimitedFn(5) .then((result) => console.log(result)) .catch((err) => console.log(err)); // Output: 25

Example 3:

const timeLimitedFn = timeLimit(async (a, b) => { await new Promise((res) => setTimeout(res, 120)); return a + b; }, 150); timeLimitedFn(5, 10) .then((result) => console.log(result)) .catch((err) => console.log(err)); // Output: 15

Example 4:

const timeLimitedFn = timeLimit(async () => { throw "Error"; }, 1000); timeLimitedFn() .then((result) => console.log(result)) .catch((err) => console.log(err)); // Output: "Error"

Keep in mind the following constraints:

  • 0 <= inputs.length <= 10
  • 0 <= t <= 1000
  • fn returns a promise

In this lab, you will be required to complete the following challenges:

  1. Implement the timeLimit function.
  2. Test the timeLimit function with various test cases and ensure that they are passing.
  3. Write the evaluation script to evaluate your implementation.

Good luck, and happy coding!