Skip to content

Instantly share code, notes, and snippets.

@yongjun21
Last active May 29, 2023 02:55
Show Gist options
  • Save yongjun21/f12018ea673213a68b834b8defa28b76 to your computer and use it in GitHub Desktop.
Save yongjun21/f12018ea673213a68b834b8defa28b76 to your computer and use it in GitHub Desktop.
Complete implementation of Promise.map
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