Skip to content

Commit

Permalink
fix: catch toString and String() usage
Browse files Browse the repository at this point in the history
  • Loading branch information
RedTn committed Sep 28, 2020
1 parent 2b0d70c commit cb92bd2
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
34 changes: 34 additions & 0 deletions lib/rules/no-array-index-key.js
Expand Up @@ -150,6 +150,40 @@ module.exports = {
identifiers.filter(isArrayIndex).forEach(() => {
context.report({node, message: ERROR_MESSAGE});
});

return;
}

if (node.type === 'CallExpression'
&& node.callee
&& node.callee.type === 'MemberExpression'
&& node.callee.object
&& isArrayIndex(node.callee.object)
&& node.callee.property
&& node.callee.property.type === 'Identifier'
&& node.callee.property.name === 'toString'
) {
// key={bar.toString()}
context.report({
node,
message: ERROR_MESSAGE
});
return;
}

if (node.type === 'CallExpression'
&& node.callee
&& node.callee.type === 'Identifier'
&& node.callee.name === 'String'
&& Array.isArray(node.arguments)
&& node.arguments.length > 0
&& isArrayIndex(node.arguments[0])
) {
// key={String(bar)}
context.report({
node: node.arguments[0],
message: ERROR_MESSAGE
});
}
}

Expand Down
26 changes: 26 additions & 0 deletions tests/lib/rules/no-array-index-key.js
Expand Up @@ -75,6 +75,22 @@ ruleTester.run('no-array-index-key', rule, {
code: 'foo.map((baz, i) => <Foo key />)'
},

{
code: 'foo.map((bar, i) => <Foo key={i.baz.toString()} />)'
},

{
code: 'foo.map((bar, i) => <Foo key={i.toString} />)'
},

{
code: 'foo.map((bar, i) => <Foo key={String()} />)'
},

{
code: 'foo.map((bar, i) => <Foo key={String(baz)} />)'
},

{
code: 'foo.reduce((a, b) => a.concat(<Foo key={b.id} />), [])'
},
Expand Down Expand Up @@ -119,6 +135,16 @@ ruleTester.run('no-array-index-key', rule, {
errors: [{message: 'Do not use Array index in keys'}]
},

{
code: 'foo.map((bar, i) => <Foo key={i.toString()} />)',
errors: [{message: 'Do not use Array index in keys'}]
},

{
code: 'foo.map((bar, i) => <Foo key={String(i)} />)',
errors: [{message: 'Do not use Array index in keys'}]
},

{
code: 'foo.map((bar, anything) => <Foo key={anything} />)',
errors: [{message: 'Do not use Array index in keys'}]
Expand Down

0 comments on commit cb92bd2

Please sign in to comment.