Skip to content

Commit 42a03ab

Browse files
perf: use improved comparison algorithm
This change reduces the time for this rule on the eslint repo down from 453ms to 46ms (= roughly 8x faster).
1 parent 305c7cd commit 42a03ab

File tree

1 file changed

+14
-34
lines changed

1 file changed

+14
-34
lines changed

lib/rules/no-identical-tests.js

+14-34
Original file line numberDiff line numberDiff line change
@@ -38,48 +38,28 @@ module.exports = {
3838
// Helpers
3939
// ----------------------------------------------------------------------
4040
/**
41-
*compare two test cases despite of properties order.
42-
*@returns {boolean} if eq, return true, else return false.
41+
* Create a unique cache key
42+
* @param {object} test
43+
* @returns {string}
4344
*/
44-
function eq(testA, testB) {
45-
if (testA.type !== testB.type) {
46-
return false;
45+
function toKey(test) {
46+
if (test.type !== 'ObjectExpression') {
47+
return JSON.stringify([test.type, sourceCode.getText(test)]);
4748
}
48-
49-
if (testA.type !== 'ObjectExpression') {
50-
return sourceCode.getText(testA) === sourceCode.getText(testB);
51-
}
52-
53-
const propertiesA = testA.properties;
54-
const propertiesB = testB.properties;
55-
56-
// if properties length not eq; return false;
57-
if (propertiesA.length !== propertiesB.length) {
58-
return false;
59-
}
60-
61-
const propertiesSetA = new Set();
62-
propertiesA.forEach((item) => {
63-
const code = sourceCode.getText(item);
64-
propertiesSetA.add(code);
65-
});
66-
67-
for (const element of propertiesB) {
68-
const code = sourceCode.getText(element);
69-
if (!propertiesSetA.has(code)) {
70-
return false;
71-
}
72-
}
73-
return true;
49+
return JSON.stringify([
50+
test.type,
51+
...test.properties.map((p) => sourceCode.getText(p)).sort(),
52+
]);
7453
}
7554

7655
return {
7756
Program(ast) {
7857
utils.getTestInfo(context, ast).forEach((testRun) => {
7958
[testRun.valid, testRun.invalid].forEach((tests) => {
80-
const cache = [];
59+
const cache = new Set();
8160
tests.forEach((test) => {
82-
if (cache.some((item) => eq(item, test))) {
61+
const key = toKey(test);
62+
if (cache.has(key)) {
8363
context.report({
8464
node: test,
8565
messageId: 'identical',
@@ -96,7 +76,7 @@ module.exports = {
9676
},
9777
});
9878
} else {
99-
cache.push(test);
79+
cache.add(key);
10080
}
10181
});
10282
});

0 commit comments

Comments
 (0)