Middle+
Implement a function smartFetch, which is a wrapper over batchFetch for data requests from the backend by ID. The function should accumulate calls within a time window (timeout) and send them as a single batch request. The wait for the next window starts immediately after sending the request. IDs are unique, fetch is always successful. Properly handle the case when duplicate IDs arrive within the same window.
sobes.tech AI
Answer from AI
javascript function smartFetch(batchFetch, timeout) { let queue = new Map(); // id -> [resolve, reject] let timer = null;
function flush() { const ids = Array.from(queue.keys()); const resolvers = Array.from(queue.values()); queue = new Map(); timer = null;
batchFetch(ids).then(results => {
// results - array of data in the same order as ids
results.forEach((result, index) => {
resolvers[index].resolve(result);
});
});
}
return function(id) { return new Promise((resolve, reject) => { if (!queue.has(id)) { queue.set(id, {resolve, reject}); } else { // If id already exists, add another resolve to ensure all calls get a response const old = queue.get(id); // Convert to array if needed if (Array.isArray(old)) { old.push({resolve, reject}); queue.set(id, old); } else { queue.set(id, [old, {resolve, reject}]); } }
if (!timer) {
timer = setTimeout(flush, timeout);
}
});
}; }