Last active
September 4, 2024 06:28
-
-
Save yongjun21/2ed6edcc2b3d850414d7d4310a848a98 to your computer and use it in GitHub Desktop.
Complete implementation of Promise.filter
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.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