Skip to content

Instantly share code, notes, and snippets.

@stuartambient
Last active Feb 1, 2021
Embed
What would you like to do?
NodeJS Design Patters (third edition) challenges
function mapAsync(iterable, callback, concurrency, results) {
if (!iterable.length)
return Promise.all(results).then(results => console.log(results));
const queue = iterable.splice(0, concurrency - 1);
while (queue.length) {
const task = queue.shift();
callback(task, iterable, callback, concurrency, results);
}
}
function callback(task, iterable, callback, concurrency, results) {
results.push(
new Promise((resolve, reject) => {
if (typeof task === 'function') {
resolve(task());
} else {
resolve(task);
}
})
);
mapAsync(iterable, callback, concurrency, results);
}
// using funciton for final results
const funcs = [
() => [1, new Date().getMilliseconds()],
() => [2, new Date().getMilliseconds()],
() => [3, new Date().getMilliseconds()],
() => [4, new Date().getMilliseconds()],
() => [5, new Date().getMilliseconds()],
];
// simple values
const ab = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
mapAsync(funcs, callback, 2, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment