Skip to content

Commit

Permalink
Rule fix: no-extend: Only fix if first arg is object literal
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 committed Jun 21, 2024
1 parent bd0218c commit d1cf17f
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
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, bar)',
options: [ { allowDeep: true } ],
errors: [ error ]
}
]
} );

0 comments on commit d1cf17f

Please sign in to comment.