Last active
October 30, 2021 19:18
-
-
Save gaogao-9/bac4fbcb7f6b6a045a6f to your computer and use it in GitHub Desktop.
正しいPromise.reverseとPromise.anyの実装例
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.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)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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