Skip to content

Instantly share code, notes, and snippets.

@gaogao-9
Last active October 30, 2021 19:18
Show Gist options
  • Save gaogao-9/bac4fbcb7f6b6a045a6f to your computer and use it in GitHub Desktop.
Save gaogao-9/bac4fbcb7f6b6a045a6f to your computer and use it in GitHub Desktop.
正しいPromise.reverseとPromise.anyの実装例
Promise.reverse = function reverse(promise){
// 範囲を広げるために、一応instanceof Promiseではなく、thenableを通すようにしてる。
switch(true){
case (typeof(promise) !== "object"):
case (promise === null):
case (typeof(promise.then) !== "function"):
return Promise.reject(promise);
}
return promise.then((data)=> Promise.reject(data), (err)=> Promise.resolve(err));
};
Promise.any = function any(iterable){
return Promise.reverse(Promise.all([...iterable].map(Promise.reverse)));
};
// 見た目の美しさだと↑なんだけど、速度重視ならfor使った↓ほうがいいかもね
Promise.any = function any(iterable){
const promises = [];
for(const promise of iterable){
promises.push(Promise.reverse(promise));
}
return Promise.reverse(Promise.all(promises));
};
@dalisoft
Copy link

@gaogao-9 I should say, even after 5-years later, you is genius. I not able to solve in interview and then seen your solution from promise-any PR. Very amazing and simple

@gaogao-9
Copy link
Author

@dalisoft Glad it helped!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment