Last active
February 1, 2021 22:38
-
-
Save stuartambient/24641833137b50e653a451cbca2c13d2 to your computer and use it in GitHub Desktop.
NodeJS Design Patters (third edition) challenges
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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