Skip to content

Commit 72918bc

Browse files
committed
fix: Added util functions and util tests.
Fix: Added util functions and util tests. fix: Changed regex. fix: tests.
1 parent 060222b commit 72918bc

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

src/util/util.ts

+27-1
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,29 @@ function writeFile(path: string, file: string, encoding?: string): any {
8383
});
8484
}
8585

86+
const evalReg = new RegExp(/\beval\(([^),]*)\)/g);
87+
88+
// hasEval determine whether matcher contains function eval
89+
function hasEval(s: string): boolean {
90+
return evalReg.test(s);
91+
}
92+
93+
// replaceEval replace function eval with the value of its parameters
94+
function replaceEval(s: string, rule: string): string {
95+
return s.replace(evalReg, '(' + rule + ')');
96+
}
97+
98+
// getEvalValue returns the parameters of function eval
99+
function getEvalValue(s: string): string[] {
100+
const subMatch: any = s.match(evalReg);
101+
const rules: string[] = [];
102+
for (const rule of subMatch) {
103+
const index: number = rule.search('(');
104+
rules.push(rule.slice(index + 1, -1));
105+
}
106+
return rules;
107+
}
108+
86109
export {
87110
escapeAssertion,
88111
removeComments,
@@ -93,5 +116,8 @@ export {
93116
paramsToString,
94117
setEquals,
95118
readFile,
96-
writeFile
119+
writeFile,
120+
hasEval,
121+
replaceEval,
122+
getEvalValue
97123
};

test/util.test.ts

+20
Original file line numberDiff line numberDiff line change
@@ -133,3 +133,23 @@ test('test globMatch', () => {
133133
expect(util.globMatch('/prefix/subprefix/foobar', '*/foo*')).toEqual(false);
134134
expect(util.globMatch('/prefix/subprefix/foobar', '*/foo/*')).toEqual(false);
135135
});
136+
137+
test('test hasEval', () => {
138+
expect(util.hasEval('eval() && a && b && c')).toEqual(true);
139+
expect(util.hasEval('eval) && a && b && c')).toEqual(false);
140+
expect(util.hasEval('eval)( && a && b && c')).toEqual(false);
141+
expect(util.hasEval('xeval() && a && b && c')).toEqual(false);
142+
expect(util.hasEval('eval(c * (a + b)) && a && b && c')).toEqual(true);
143+
});
144+
145+
test('test replaceEval', () => {
146+
expect(util.replaceEval('eval() && a && b && c', 'a')).toEqual('(a) && a && b && c');
147+
expect(util.replaceEval('eval() && a && b && c', '(a)')).toEqual('((a)) && a && b && c');
148+
});
149+
150+
test('test getEvalValue', () => {
151+
expect(util.getEvalValue('eval(a) && a && b && c')).isEqual(['a']);
152+
expect(util.getEvalValue('a && eval(a) && b && c')).isEqual(['a']);
153+
expect(util.getEvalValue('eval(a) && eval(b) && a && b && c')).isEqual(['a', 'b']);
154+
expect(util.getEvalValue('a && eval(a) && eval(b) && b && c')).isEqual(['a', 'b']);
155+
});

0 commit comments

Comments
 (0)