Skip to content
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

Catch replace in no-array-prototype-extensions rule #1476

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/rules/no-array-prototype-extensions.js
Expand Up @@ -28,7 +28,7 @@ const EXTENSION_METHODS = new Set([
'without',
/**
* https://api.emberjs.com/ember/release/classes/MutableArray
* MutableArray methods excluding `replace` since it's part of string native functions
* MutableArray methods excluding `replace`. `replace` is handled differently as it's also part of String.prototype.
* */
'addObject',
'addObjects',
Expand All @@ -47,6 +47,8 @@ const EXTENSION_METHODS = new Set([
'unshiftObjects',
]);

const REPLACE_METHOD = 'replace';

/**
* https://api.emberjs.com/ember/release/classes/EmberArray
* EmberArray properties excluding native props: [], length.
Expand Down Expand Up @@ -98,6 +100,13 @@ module.exports = {
if (EXTENSION_METHODS.has(node.callee.property.name)) {
context.report({ node, messageId: 'main' });
}

// Example: someArray.replace(1, 2, [1, 2, 3]);
// We can differentiate String.prototype.replace and Array.prototype.replace by arguments length
// String.prototype.replace can only have 2 arguments, Array.prototype.replace needs to have exact 3 arguments
if (node.callee.property.name === REPLACE_METHOD && node.arguments.length === 3) {
context.report({ node, messageId: 'main' });
}
},

/**
Expand Down
14 changes: 11 additions & 3 deletions tests/lib/rules/no-array-prototype-extensions.js
Expand Up @@ -33,12 +33,15 @@ ruleTester.run('no-array-prototype-extensions', rule, {
'something[something.length - 1]',
'something.isAny',
"something['compact']",
'replace()',
'replace(foo)',
'replace(foo, bar, baz)',
/** Optional chaining */
'arr?.notfirstObject?.foo',
'arr?.filter?.()',
/** Replace is part of string native prototypes */
"'something'.replace()",
'something.replace()',
/** String.prototype.replace() */
"'something'.replace(regexp, 'substring')",
"something.replace(regexp, 'substring')",
smilland marked this conversation as resolved.
Show resolved Hide resolved
],
invalid: [
{
Expand Down Expand Up @@ -272,5 +275,10 @@ ruleTester.run('no-array-prototype-extensions', rule, {
output: null,
errors: [{ messageId: 'main', type: 'CallExpression' }],
},
{
code: 'something.replace(1, 2, someArray)',
output: null,
errors: [{ messageId: 'main', type: 'CallExpression' }],
},
],
});