-
Notifications
You must be signed in to change notification settings - Fork 132
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
实现一个异步求和函数 #109
Comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
简化:两数之和
我们先来简单的实现一个异步两数之和函数
加深:多数之和
上面我们实现了两数之和,然后扩展到多数之和喃?
提到数组求和问题,我们首先想到的是
reduce
callback
函数接收4个参数:acc
:累计器cur
:当前值idx
: 当前索引arr
:源数组其中,
initialValue
可选,initialValue
:acc
取值为initialValue
,cur
取数组中的第一个值acc
取数组中的第一个值,cur
取数组中的第二个值关于本题:来自@champkeh
设置初始值为
Promise.resolve(0)
,经历5
次求和:但这存在一个耗时较长的问题,我们可以计算下时间:
也就是说,我们每次求和都会花费 1s,串行异步求和,这显然不是最优的
优化:使用 Promise.all
我们可以两两一组,使用
Promise.all
求和,再把和两两一组继续求和…..,知道只剩余一个就是最终的结果The text was updated successfully, but these errors were encountered: