-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
61 lines (57 loc) · 1.58 KB
/
index.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
58
59
60
61
export interface TargetFunction {
(params: object, page?: number, size?: number): Promise<{ data: any[]; total: number }>
}
export interface AsyncIterator {
next(): Promise<{ done: boolean; value: any[]; total: number }>
}
/**
* 创建同步迭代去
* @param array 数组
* @param step 步长
*/
export const createIterator = (array: [], step = 1) => {
let nextIndex = 0
return {
next() {
if (nextIndex < array.length) {
const startIndex = nextIndex
const endIndex = startIndex + step
nextIndex += step
return {
value: array.slice(startIndex, endIndex),
}
}
return { done: true }
},
}
}
/**
* 创建异步迭代器
* @param array
* @param step
*/
export const createAsyncIterator = (targetFunction: TargetFunction, params: object = {}, size = 10) => {
const doneData = { done: true, value: [], total: 0 }
let page = 1 // 页码
let totalData: number // 数据总长度
return {
async next() {
if (page === 1) {
const { total, data } = await targetFunction(params, page, size)
totalData = total
if (totalData === 0) {
return doneData
}
page += 1
return { done: total <= size, value: data, total }
}
if (totalData - (page - 1) * size > 0) {
const { data } = await targetFunction(params, page, size)
page += 1
return { done: totalData <= page * size, value: data, total: totalData }
}
return { ...doneData, total: totalData }
},
}
}
export default { createIterator, createAsyncIterator }