Skip to content

Commit

Permalink
Rule fix: no-extend: Only fix if first arg is object literal (#330)
Browse files Browse the repository at this point in the history
If the first argument is a variable which could be null
or undefined, then Object.assign will throw.

We could convert to `Object.assign( foo || {}, ... )` but in
most cases this is unnecessary, so probably better to leave
it to users to fix manually.
  • Loading branch information
edg2s authored Jun 24, 2024
1 parent f3e29be commit 35d4489
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 1 deletion.
1 change: 1 addition & 0 deletions docs/rules/no-extend.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ $.extend( { myUtil: fn } );
❌ Examples of **incorrect** code with `[{"allowDeep":true}]` options:
```js
$.extend( {}, foo );
$.extend( fooCouldBeNull, doesNotAutofix );
```

✔️ Examples of **correct** code with `[{"allowDeep":true}]` options:
Expand Down
4 changes: 3 additions & 1 deletion src/rules/no-extend.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ module.exports = {
node,
message: 'Prefer Object.assign or the spread operator to $.extend',
fix: function ( fixer ) {
if ( !isDeep ) {
// Only auto-fix if we are sure the first argument is an object.
// If it is undefined or null variable, then Object.assign will throw.
if ( !isDeep && node.arguments[ 0 ] && node.arguments[ 0 ].type === 'ObjectExpression' ) {
return fixer.replaceText( node.callee, 'Object.assign' );
}
}
Expand Down
5 changes: 5 additions & 0 deletions tests/rules/no-extend.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ ruleTester.run( 'no-extend', rule, {
options: [ { allowDeep: true } ],
errors: [ error ],
output: 'Object.assign({}, foo)'
},
{
code: '$.extend(fooCouldBeNull, doesNotAutofix)',
options: [ { allowDeep: true } ],
errors: [ error ]
}
]
} );

0 comments on commit 35d4489

Please sign in to comment.