-
Notifications
You must be signed in to change notification settings - Fork 31
/
分治的迭代写法.ts
57 lines (48 loc) · 1.39 KB
/
分治的迭代写法.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* eslint-disable max-len */
// 分治的迭代写法
// 用于并行执行任务,例如异步求加法等
async function mergeAllAsync<T>(items: Array<Promise<T>>, e: () => Promise<T>, op: (e1: Promise<T>, e2: Promise<T>) => Promise<T>): Promise<T> {
if (!items.length) return e()
const copy = items.slice()
let n = copy.length
while (n > 1) {
const mid = (n + 1) >> 1
for (let i = 0; i < mid; i++) {
// "!==n"
if (((i << 1) | 1) ^ n) {
copy[i] = op(copy[i << 1], copy[(i << 1) | 1]) // !TODO:这里可以Promise.all 并行计算这些分组的答案
} else {
copy[i] = copy[i << 1]
}
}
n = mid
}
return copy[0]
}
function mergeAll<T>(items: ArrayLike<T>, e: () => T, op: (e1: T, e2: T) => T): T {
if (!items.length) return e()
const copy = Array(items.length)
for (let i = 0; i < items.length; i++) copy[i] = items[i]
let n = copy.length
while (n > 1) {
const mid = (n + 1) >>> 1
for (let i = 0; i < mid; i++) {
if (((i << 1) | 1) ^ n) {
copy[i] = op(copy[i << 1], copy[(i << 1) | 1])
} else {
copy[i] = copy[i << 1]
}
}
n = mid
}
return copy[0]
}
if (require.main === module) {
const sum = mergeAll(
[1, 2, 3, 4, 5, 6, 7],
() => 0,
(a, b) => a + b
)
console.log(sum)
}
export { mergeAll, mergeAllAsync }