Skip to content

Commit ec604c6

Browse files
committed
Add support for functions, chaining, etc
1 parent b8bef10 commit ec604c6

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

lib/rules/sort.js

+30-4
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,25 @@ function isDependencyArrayHook(node) {
2121
/** @type {import('eslint').Rule.RuleModule} */
2222
module.exports = {
2323
create(context) {
24+
function getSortableNameFromNode(node) {
25+
if (!node) return '';
26+
27+
switch (node.type) {
28+
case 'Identifier':
29+
return node.name;
30+
case 'MemberExpression':
31+
// For chained expressions, e.g., `a.b.c`, we'll return `a.b.c`
32+
return (
33+
getSortableNameFromNode(node.object) +
34+
'.' +
35+
getSortableNameFromNode(node.property)
36+
);
37+
default:
38+
// For any other types or for simplicity, you could just stringify the node.
39+
return context.getSourceCode().getText(node);
40+
}
41+
}
42+
2443
return {
2544
CallExpression(node) {
2645
if (isDependencyArrayHook(node.callee)) {
@@ -33,12 +52,19 @@ module.exports = {
3352
) {
3453
const currentDependencies = [...dependencies.elements];
3554
const currentNames = currentDependencies.map(
36-
(item) => item.name
55+
getSortableNameFromNode
3756
);
3857

39-
const sortedDependencies = [
40-
...dependencies.elements,
41-
].sort((a, b) => (a.name < b.name ? -1 : 1));
58+
const sortedDependencies = [...dependencies.elements]
59+
.map((n) => ({
60+
...n,
61+
name: getSortableNameFromNode(n),
62+
}))
63+
.sort((a, b) =>
64+
a.name
65+
.toLowerCase()
66+
.localeCompare(b.name.toLowerCase())
67+
);
4268
const sortedNames = sortedDependencies.map(
4369
(item) => item.name
4470
);

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "eslint-plugin-sort-react-dependency-arrays",
33
"description": "ESLint plugin to alphabetically sort React hook dependency arrays",
4-
"version": "0.2.0",
4+
"version": "0.3.0",
55
"author": "Steven Sacks <[email protected]>",
66
"keywords": [
77
"eslint",

0 commit comments

Comments
 (0)