Skip to content

perf: use improved comparison algorithm in no-identical-tests rule #337

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 20, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 14 additions & 34 deletions lib/rules/no-identical-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,48 +38,28 @@ module.exports = {
// Helpers
// ----------------------------------------------------------------------
/**
*compare two test cases despite of properties order.
*@returns {boolean} if eq, return true, else return false.
* Create a unique cache key
* @param {object} test
* @returns {string}
*/
function eq(testA, testB) {
if (testA.type !== testB.type) {
return false;
function toKey(test) {
if (test.type !== 'ObjectExpression') {
return JSON.stringify([test.type, sourceCode.getText(test)]);
}

if (testA.type !== 'ObjectExpression') {
return sourceCode.getText(testA) === sourceCode.getText(testB);
}

const propertiesA = testA.properties;
const propertiesB = testB.properties;

// if properties length not eq; return false;
if (propertiesA.length !== propertiesB.length) {
return false;
}

const propertiesSetA = new Set();
propertiesA.forEach((item) => {
const code = sourceCode.getText(item);
propertiesSetA.add(code);
});

for (const element of propertiesB) {
const code = sourceCode.getText(element);
if (!propertiesSetA.has(code)) {
return false;
}
}
return true;
return JSON.stringify([
test.type,
...test.properties.map((p) => sourceCode.getText(p)).sort(),
]);
}

return {
Program(ast) {
utils.getTestInfo(context, ast).forEach((testRun) => {
[testRun.valid, testRun.invalid].forEach((tests) => {
const cache = [];
const cache = new Set();
tests.forEach((test) => {
if (cache.some((item) => eq(item, test))) {
const key = toKey(test);
if (cache.has(key)) {
context.report({
node: test,
messageId: 'identical',
Expand All @@ -96,7 +76,7 @@ module.exports = {
},
});
} else {
cache.push(test);
cache.add(key);
}
});
});
Expand Down