Skip to content

Commit 7d13e09

Browse files
committed
feat(utils): add mini-chainFn
1 parent b2c5cd1 commit 7d13e09

File tree

1 file changed

+54
-3
lines changed

1 file changed

+54
-3
lines changed

docs/docs/utils.md

+54-3
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ export class ChainFn {
2929
executor && this.executorList.push([executor, args]);
3030
}
3131

32-
public add(onResFn: ExecutorFn, args?: any) {
32+
public add(onResFn: ExecutorFn, ...args: any[]) {
3333
args = flat([args]);
3434
return new ChainFn(onResFn, args, this.resList, this.executorList, this.errorList);
3535
}
@@ -38,7 +38,7 @@ export class ChainFn {
3838
return executor instanceof Promise ? await (executor as any).apply(this, args) : executor.apply(this, args);
3939
}
4040

41-
public async run(onResFn?: Function, args?: any): Promise<ChainFn> {
41+
public async run(onResFn?: Function, ...args: any[]): Promise<ChainFn> {
4242
await this.getValue();
4343
args = flat([args]);
4444

@@ -60,7 +60,6 @@ export class ChainFn {
6060

6161
public async get(allRes = false): Promise<any> {
6262
await this.getValue();
63-
this.resList = this.resList.filter(v => v);
6463
return allRes ? this.resList : this.resList[this.resList.length-1];
6564
}
6665

@@ -113,4 +112,56 @@ console.log(await new ChainFn()
113112
* 7
114113
* 7 最后的结果
115114
*/
115+
```
116+
117+
### mini-chainFn (only sync)
118+
```ts
119+
type ExecutorFn = (...args: any) => any;
120+
121+
export const flat = (arr: any[], num = 1) => {
122+
let i = 0;
123+
while (arr.some((item) => Array.isArray(item))) {
124+
arr = [].concat(...arr);
125+
i++;
126+
if (i >= num) break;
127+
}
128+
return arr;
129+
};
130+
131+
export class ChainFn {
132+
resList!: any[];
133+
134+
constructor(executor?: ExecutorFn, args?: any, resList: any[] = []) {
135+
this.initValue(resList);
136+
args = flat([args]);
137+
// 执行对应方法
138+
const returnValue = executor?.apply(this, args!);
139+
140+
returnValue && this.resList.push(returnValue);
141+
}
142+
143+
public initValue(resList: any[]) {
144+
this.resList = resList;
145+
}
146+
147+
public add(onResFn: ExecutorFn, args: any) {
148+
args = flat([args]);
149+
return new ChainFn(onResFn, args, this.resList);
150+
}
151+
152+
// eslint-disable-next-line @typescript-eslint/ban-types
153+
public run(onResFn: Function, args: any) {
154+
try {
155+
args = flat([args]);
156+
const returnValue = onResFn.apply(this, [this.resList, ...args]);
157+
if (returnValue) return returnValue;
158+
} catch (error) {
159+
console.warn(error);
160+
}
161+
}
162+
163+
public remove() {
164+
return new ChainFn(undefined, undefined, []);
165+
}
166+
}
116167
```

0 commit comments

Comments
 (0)