-
-
Save kanrong/9c9f62c4bc94857df9e762cc66f5b075 to your computer and use it in GitHub Desktop.
Complete implementation of Promise.filter
This file contains hidden or 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