Sobes.tech
Middle

/* * Function that emulates requesting data from backend. * Backend has RPS limitation, and will fail, * if parallel requests number is more than MAX_PARALLEL_REQUESTS. */ function requestData(id: number): Promise<string> { parallelRequests++; if (parallelRequests > MAX_PARALLEL_REQUESTS) { throw new Error("Too many parallel requests"); } return new Promise((res) => { setTimeout(() => { parallelRequests--; return res(`${id * 2}`); }, Math.floor(Math.random() * 2000)) }); } function prepareData( ids: number[], maxParallelRequests: number, ): Promise<string[]> { /* * TODO: implement requesting all data, * using no more than maxParallelRequests * parallel connections. */ }

sobes.tech AI

Answer from AI

To implement the prepareData function, which requests data with a limit on the number of parallel requests, you can use a queue and control the number of concurrent requestData calls.

Here's an example implementation using async/await and a loop:

async function prepareData(ids: number[], maxParallelRequests: number): Promise<string[]> {
  const results: string[] = [];
  let index = 0;

  // Function to run a single request and save the result
  async function worker() {
    while (index < ids.length) {
      const currentIndex = index++;
      try {
        results[currentIndex] = await requestData(ids[currentIndex]);
      } catch (e) {
        results[currentIndex] = `Error: ${(e as Error).message}`;
      }
    }
  }

  // Launch maxParallelRequests workers
  const workers = [];
  for (let i = 0; i < maxParallelRequests; i++) {
    workers.push(worker());
  }

  await Promise.all(workers);
  return results;
}

The idea is that we launch several "workers," each of which processes elements of the ids array sequentially until they are exhausted. This way, no more than maxParallelRequests requests will be executed simultaneously, which matches the backend's limit.

/* * Function that emulates requesting data from… - sobes.tech