Skip to content

Instantly share code, notes, and snippets.

@oamaok
Created January 4, 2017 16:20
Show Gist options
  • Save oamaok/6bbb05f817858a7c230b3bfbc24cc505 to your computer and use it in GitHub Desktop.
Save oamaok/6bbb05f817858a7c230b3bfbc24cc505 to your computer and use it in GitHub Desktop.
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