Created
January 4, 2017 16:20
-
-
Save oamaok/6bbb05f817858a7c230b3bfbc24cc505 to your computer and use it in GitHub Desktop.
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
class AsyncArray { | |
constructor(value) { | |
this.promise = Promise.resolve(value); | |
} | |
filter(fn) { | |
const promise = this.promise.then(value => Promise.all([ | |
Promise.all(value.map(fn)), | |
value, | |
])) | |
.then(([bools, value]) => value.filter((item, index) => bools[index])); | |
return new AsyncArray(promise); | |
} | |
map(fn) { | |
const promise = this.promise.then(value => Promise.all(value.map(fn))); | |
return new AsyncArray(promise); | |
} | |
reduce(fn, initial) { | |
return this.promise.then(value => value.reduce((promise, item, index) => | |
promise.then(innerValue => fn(innerValue, item, index)), | |
Promise.resolve(initial) | |
)); | |
} | |
value() { | |
return this.promise; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment