UNPKG

2.14 kBJavaScriptView Raw
1class Explore {
2 constructor() {
3 this.parseFunction = null;
4 this.root = null;
5 this.callback = this.error = () => {}
6 }
7 parse(f) { //f是一个promise函数
8 this.parseFunction = f;
9 return this;
10 }
11 setCallback(f) {
12 this.callback = f;
13 return this;
14 }
15 setError(f) {
16 this.error = f;
17 return this;
18 }
19 trace(inputObj,lastInputObj){
20 let ts=this;
21 return function(){
22 let complete = true;
23 for (let val of inputObj.children) {
24 if (val.status !== 'done') {
25 complete = false;
26 break;
27 }
28 }
29 if (complete === false) {
30 return false;
31 }
32 inputObj.status = 'done';
33 if (lastInputObj === null) { //如果没有则微顶部内容
34 ts.callback();
35 } else {
36 lastInputObj.trace();
37 }
38 }
39 }
40 run(opt) { //开始输入一串内容
41 let {
42 lastInputObj = null, input
43 } = opt
44 let {
45 parseFunction,root
46 } = this;
47 let ts = this;
48 let inputObj={
49 status: 'pending',
50 value: input,
51 children: []
52 };
53 inputObj.trace =ts.trace(inputObj,lastInputObj)
54 if (root === null) {
55 this.root = inputObj;
56 } else {
57 lastInputObj.children.push(inputObj); //如果不是根元素
58 }
59 let lastVal=lastInputObj===null?null:lastInputObj.value;
60 //解析
61 parseFunction(input,lastVal)
62 .then((outputs) => { //解析返回多个内容
63 if (Array.isArray(outputs)) { //只要有output,并且output是数组就继续
64 let lg = outputs.length;
65 if (lg === 0) { //如果没有子元素了
66 inputObj.trace();
67 } else {
68 outputs.forEach((output, ind) => {
69 ts.run({
70 input: output,
71 lastInputObj: inputObj
72 })
73 });
74 }
75 } else {
76 inputObj.trace(); //也会直接回溯
77 }
78 })
79 .catch((err)=>{
80 ts.error(err);
81 }) ;
82 return this;
83 }
84}
85
86
87module.exports=Explore;
88// export default Explore;
\No newline at end of file