Skip to content

Instantly share code, notes, and snippets.

@yongjun21
Last active September 4, 2024 06:28
Show Gist options
  • Save yongjun21/2ed6edcc2b3d850414d7d4310a848a98 to your computer and use it in GitHub Desktop.
Save yongjun21/2ed6edcc2b3d850414d7d4310a848a98 to your computer and use it in GitHub Desktop.
Complete implementation of Promise.filter
Promise.filter = function (iterable, filterer, options = {}) {
let concurrency = options.concurrency || Infinity
let index = 0
const results = []
const predicates = []
const pending = []
const iterator = iterable[Symbol.iterator]()
while (concurrency-- > 0) {
const pending = wrappedFilterer()
if (pending) pending.push(promise)
else break
}
return Promise.all(pending).then(() => results.filter((v, i) => predicates[i]))
function wrappedFilterer () {
const next = iterator.next()
if (next.done) return null
const i = index++
results.push(next.value)
const predicate = filterer(next.value, i)
return Promise.resolve(predicate).then(resolved => {
predicates[i] = resolved
return wrappedFilterer()
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment