Middle
/** * Implement the function that will execute a callback with the data * and return an array of responses Response[]. * The solution should execute all requests in parallel * but no more than [limit] requests can be executed concurrently. * The goal is to minimize the total execution time. */ type Props<RequestData, Response> = { callback: (args: RequestData) => Promise<Response>; data: Array<RequestData>; limit: number; }; export async function runWithLimit<RequestData, Response>({ callback, data, limit, }: Props<RequestData, Response>): Promise<Response[]> { // START SOLUTION HERE if (limit < 1 || data.length === 0) { return Promise.resolve([]); } if (limit >= data.length) { return Promise.all(data.map(callback)); } const result: Response[] = new Array(data.length); let index = 0; const run = async () => { if (index >= data.length) return; const elem = data[index]; try { result[index] = await callback(elem); } catch (err) { result[index] = (err) as Response; // todo: handle error } index++; run(); }; const startPack = Array.from({ length: limit }, run); await Promise.all(startPack); return result; }
sobes.tech AI
Answer from AI
The runWithLimit function implements parallel execution of asynchronous requests with a limit on the maximum number of concurrently running requests (limit).
Main idea of the solution:
- If the limit is greater than or equal to the number of requests, all are started at once using
Promise.all. - Otherwise, exactly
limitparallel tasks are started. - Each task, after completing, launches the next one from the queue until all data is processed.
This allows efficient use of parallelism without exceeding the set limit.
Example of usage:
const results = await runWithLimit({
callback: async (url: string) => {
const response = await fetch(url);
return response.json();
},
data: ['url1', 'url2', 'url3', 'url4'],
limit: 2,
});
console.log(results);
Thus, no more than 2 requests will be executed simultaneously, helping to control the load.