-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
111 lines (91 loc) · 2.32 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
type TGlobalVarObj = {[index: string]: any};
interface IInject {
condition: boolean;
func: (globalVar?: TGlobalVarObj) => void;
tag?: string;
}
interface IStack {
condition: boolean;
func: (globalVar?: TGlobalVarObj) => void;
parent: string;
self: string;
}
export default class Akua {
private stack: IStack[] = [];
private separator = '->';
private globalVarObj = {};
private isValidTag (tag: string) {
const reuslt = {
self: '',
parent: '',
};
const tagArr = tag.split(this.separator);
if (tagArr.length === 1) {
reuslt.self = tagArr[0];
} else if (tagArr.length === 2) {
if (tagArr.indexOf('') !== -1) {
throw(new Error('tag !=== \'\'!!!!!'));
}
reuslt.parent = tagArr[0];
reuslt.self = tagArr[1];
if (this.getTagIndex(reuslt.parent) === -1) {
throw(new Error(`tag '${reuslt.parent}' is not existed!`));
}
if (this.getTagIndex(reuslt.self) !== -1) {
throw(new Error(`tag '${reuslt.self}'is existed!`));
}
} else {
throw(new Error('tag is incorrect! eg: a or a->b'));
}
return reuslt;
}
checkParent(parent: string): boolean {
const obj = this.stack[this.getTagIndex(parent)];
if (obj.parent !== '' && obj.condition) {
return this.checkParent(obj.parent);
}
return obj.condition;
}
// get tag index
getTagIndex(parent: string) {
for (let index = 0; index < this.stack.length; index++) {
const element = this.stack[index];
if (element.self === parent) {
return index;
}
}
return -1;
}
// parse if tree, then do action
parse() {
for (const injectObj of this.stack) {
if (!injectObj.condition) {
continue;
}
if (injectObj.parent === '') {
injectObj.func(this.globalVarObj);
} else {
if (this.checkParent(injectObj.parent)) {
injectObj.func(this.globalVarObj);
}
}
}
return this;
}
/**
* inject if function
* @param obj IInject
*/
inject(condition: boolean, tag: string, func: (globalVar?: TGlobalVarObj) => void ) {
const tagObj = this.isValidTag(tag);
this.stack.push({
func: func,
condition: condition,
parent: tagObj.parent,
self: tagObj.self,
});
return this;
}
constructor() {
}
}