Last active
May 29, 2023 02:55
-
-
Save yongjun21/f12018ea673213a68b834b8defa28b76 to your computer and use it in GitHub Desktop.
Complete implementation of Promise.map
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
Promise.map = function (iterable, mapper, options = {}) { | |
let concurrency = options.concurrency || Infinity | |
let index = 0 | |
const results = [] | |
const pending = [] | |
const iterator = iterable[Symbol.iterator]() | |
while (concurrency-- > 0) { | |
const thread = wrappedMapper() | |
if (thread) pending.push(thread) | |
else break | |
} | |
return Promise.all(pending).then(() => results) | |
function wrappedMapper () { | |
const next = iterator.next() | |
if (next.done) return null | |
const i = index++ | |
const mapped = mapper(next.value, i) | |
return Promise.resolve(mapped).then(resolved => { | |
results[i] = resolved | |
return wrappedMapper() | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment