Promise Pool
Given an array of asyncronous functions functions and a pool limit n, return an asyncronous function promisePool. It should return a promise that resolves when all the input functions resolve.
Pool limit is defined as the maximum number promises that can be pending at once. promisePool should begin execution of as many functions as possible and continue executing new functions when old promises resolve. promisePool should execute functions[i] then functions[i + 1] then functions[i + 2], etc. When the last promise resolves, promisePool should also resolve.
For example, if n = 1, promisePool will execute one function at a time in series. However, if n = 2, it first executes two functions. When either of the two functions resolve, a 3rd function should be executed (if available), and so on until there are no functions left to execute.
You can assume all functions never reject. It is acceptable for promisePool to return a promise that resolves any value.
/**
* @param {Function[]} functions
* @param {number} n
* @return {Function}
*/
// TC: O(functions.length)
var promisePool = async function (functions, n) {
return new Promise((resolve) => {
let inProgress = 0, index = 0;
function helper() {
// base case
if (index >= functions.length) {
if (inProgress === 0) resolve();
return;
}
while (inProgress < n && index < functions.length) {
inProgress++;
functions[index++]().then(() => {
inProgress--;
helper();
});
}
}
helper();
});
};
/**
* const sleep = (t) => new Promise(res => setTimeout(res, t));
* promisePool([() => sleep(500), () => sleep(400)], 1)
* .then(console.log) // After 900ms
*/
type F = () => Promise<any>;
function promisePool(functions: F[], n: number): Promise<any> {
const wrappers = functions.map(fn => async () => {
await fn();
const nxt = waiting.shift();
nxt && (await nxt());
});
const running = wrappers.slice(0, n);
const waiting = wrappers.slice(n);
return Promise.all(running.map(fn => fn()));
}
This problem is about managing a pool of asynchronous functions so that no more than a set number of promises are running at any given time, similar to how a thread pool controls task execution. In JavaScript, a promise represents an asynchronous operation that eventually resolves or rejects. The goal is to process an array of functions that return promises, but only allow up to a specified limit of promises to be running simultaneously. As each promise resolves, you can immediately start the next one in the queue until all functions have been processed.
To achieve this, you need to track how many promises are currently resolving. Initially, you start by invoking exactly the limit number of promises. After that, every time one promise resolves, you can kick off the next function in the array, ensuring you never exceed the pool limit. This method keeps the number of active promises under control while ensuring that the next promise begins as soon as possible, allowing efficient processing without overwhelming the system.
Related Problems
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one repeated number in nums, return this repeated number.
You must solve the problem without modifying the array nums and uses only constant extra space.
The Hamming Distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, return the Hamming distance between them.
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively.
The geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]:
lefti is the x coordinate of the left edge of the ith building.
righti is the x coordinate of the right edge of the ith building.
heighti is the height of the ith building.
You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.
The skyline should be represented as a list of "key points" sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.
Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...]