Skip to content

Commit fc81768

Browse files
smillandhanli
andauthored
Catch replace in no-array-prototype-extensions rule (#1476)
* Support `replace` in no-array-prototype-extensions * add another test, tweak wording * Add more tests Co-authored-by: hanli <[email protected]>
1 parent 11b3c50 commit fc81768

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

lib/rules/no-array-prototype-extensions.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ const EXTENSION_METHODS = new Set([
2828
'without',
2929
/**
3030
* https://api.emberjs.com/ember/release/classes/MutableArray
31-
* MutableArray methods excluding `replace` since it's part of string native functions
31+
* MutableArray methods excluding `replace`. `replace` is handled differently as it's also part of String.prototype.
3232
* */
3333
'addObject',
3434
'addObjects',
@@ -47,6 +47,8 @@ const EXTENSION_METHODS = new Set([
4747
'unshiftObjects',
4848
]);
4949

50+
const REPLACE_METHOD = 'replace';
51+
5052
/**
5153
* https://api.emberjs.com/ember/release/classes/EmberArray
5254
* EmberArray properties excluding native props: [], length.
@@ -98,6 +100,13 @@ module.exports = {
98100
if (EXTENSION_METHODS.has(node.callee.property.name)) {
99101
context.report({ node, messageId: 'main' });
100102
}
103+
104+
// Example: someArray.replace(1, 2, [1, 2, 3]);
105+
// We can differentiate String.prototype.replace and Array.prototype.replace by arguments length
106+
// String.prototype.replace can only have 2 arguments, Array.prototype.replace needs to have exact 3 arguments
107+
if (node.callee.property.name === REPLACE_METHOD && node.arguments.length === 3) {
108+
context.report({ node, messageId: 'main' });
109+
}
101110
},
102111

103112
/**

tests/lib/rules/no-array-prototype-extensions.js

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,15 @@ ruleTester.run('no-array-prototype-extensions', rule, {
3333
'something[something.length - 1]',
3434
'something.isAny',
3535
"something['compact']",
36+
'replace()',
37+
'replace(foo)',
38+
'replace(foo, bar, baz)',
3639
/** Optional chaining */
3740
'arr?.notfirstObject?.foo',
3841
'arr?.filter?.()',
39-
/** Replace is part of string native prototypes */
40-
"'something'.replace()",
41-
'something.replace()',
42+
/** String.prototype.replace() */
43+
"'something'.replace(regexp, 'substring')",
44+
"something.replace(regexp, 'substring')",
4245
],
4346
invalid: [
4447
{
@@ -272,5 +275,10 @@ ruleTester.run('no-array-prototype-extensions', rule, {
272275
output: null,
273276
errors: [{ messageId: 'main', type: 'CallExpression' }],
274277
},
278+
{
279+
code: 'something.replace(1, 2, someArray)',
280+
output: null,
281+
errors: [{ messageId: 'main', type: 'CallExpression' }],
282+
},
275283
],
276284
});

0 commit comments

Comments
 (0)