Skip to content

Instantly share code, notes, and snippets.

@stuartambient
Last active February 1, 2021 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuartambient/24641833137b50e653a451cbca2c13d2 to your computer and use it in GitHub Desktop.
Save stuartambient/24641833137b50e653a451cbca2c13d2 to your computer and use it in GitHub Desktop.
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