Skip to content

Commit

Permalink
fix: Added util functions and util tests.
Browse files Browse the repository at this point in the history
Fix: Added util functions and util tests.

fix: Changed regex.

fix: tests.
  • Loading branch information
divy9881 committed May 6, 2020
1 parent 060222b commit 72918bc
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/util/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,29 @@ function writeFile(path: string, file: string, encoding?: string): any {
});
}

const evalReg = new RegExp(/\beval\(([^),]*)\)/g);

// hasEval determine whether matcher contains function eval
function hasEval(s: string): boolean {
return evalReg.test(s);
}

// replaceEval replace function eval with the value of its parameters
function replaceEval(s: string, rule: string): string {
return s.replace(evalReg, '(' + rule + ')');
}

// getEvalValue returns the parameters of function eval
function getEvalValue(s: string): string[] {
const subMatch: any = s.match(evalReg);
const rules: string[] = [];
for (const rule of subMatch) {
const index: number = rule.search('(');
rules.push(rule.slice(index + 1, -1));
}
return rules;
}

export {
escapeAssertion,
removeComments,
Expand All @@ -93,5 +116,8 @@ export {
paramsToString,
setEquals,
readFile,
writeFile
writeFile,
hasEval,
replaceEval,
getEvalValue
};
20 changes: 20 additions & 0 deletions test/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,23 @@ test('test globMatch', () => {
expect(util.globMatch('/prefix/subprefix/foobar', '*/foo*')).toEqual(false);
expect(util.globMatch('/prefix/subprefix/foobar', '*/foo/*')).toEqual(false);
});

test('test hasEval', () => {
expect(util.hasEval('eval() && a && b && c')).toEqual(true);
expect(util.hasEval('eval) && a && b && c')).toEqual(false);
expect(util.hasEval('eval)( && a && b && c')).toEqual(false);
expect(util.hasEval('xeval() && a && b && c')).toEqual(false);
expect(util.hasEval('eval(c * (a + b)) && a && b && c')).toEqual(true);
});

test('test replaceEval', () => {
expect(util.replaceEval('eval() && a && b && c', 'a')).toEqual('(a) && a && b && c');
expect(util.replaceEval('eval() && a && b && c', '(a)')).toEqual('((a)) && a && b && c');
});

test('test getEvalValue', () => {
expect(util.getEvalValue('eval(a) && a && b && c')).isEqual(['a']);
expect(util.getEvalValue('a && eval(a) && b && c')).isEqual(['a']);
expect(util.getEvalValue('eval(a) && eval(b) && a && b && c')).isEqual(['a', 'b']);
expect(util.getEvalValue('a && eval(a) && eval(b) && b && c')).isEqual(['a', 'b']);
});

0 comments on commit 72918bc

Please sign in to comment.