Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 23 additions & 18 deletions codemods/xtend/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import jscodeshift from 'jscodeshift';
import { removeImport } from '../shared.js';
import { ts } from '@ast-grep/napi';
import {
computeCallReplacementEdits,
removeImport,
} from '../shared-ast-grep.js';

/**
* @typedef {import('../../types.js').Codemod} Codemod
Expand All @@ -15,25 +18,27 @@ export default function (options) {
name: 'xtend',
to: 'native',
transform: ({ file }) => {
const j = jscodeshift;
const root = j(file.source);
const ast = ts.parse(file.source);
const root = ast.root();

const { identifier } = removeImport('xtend', root, j);
const { edits, localNames } = removeImport(root, 'xtend');

root
.find(j.CallExpression, {
callee: {
name: identifier,
},
})
.replaceWith(({ node }) => {
return j.objectExpression(
//@ts-ignore
node.arguments.map((arg) => j.spreadElement(arg)),
);
});
if (localNames.length === 0) {
return file.source;
}

return root.toSource(options);
const identifierName = localNames[0];
const callEdits = computeCallReplacementEdits(
root,
identifierName,
(args) => {
const spreadArgs = args.map((a) => `...${a}`);
return `{ ${spreadArgs.join(', ')} }`;
},
);
edits.push(...callEdits);

return edits.length > 0 ? root.commitEdits(edits) : file.source;
},
};
}
6 changes: 2 additions & 4 deletions test/fixtures/xtend/case-1/after.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

const assert = require('assert');

const objectA = {
Expand All @@ -11,7 +12,4 @@ const objectB = {
d: 40,
};

assert.equal({
...objectA,
...objectB
}, { a: 20, b: 2, c: 3, d: 40 });
assert.equal({ ...objectA, ...objectB }, { a: 20, b: 2, c: 3, d: 40 });
2 changes: 1 addition & 1 deletion test/fixtures/xtend/case-1/before.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ const objectB = {
d: 40,
};

assert.equal(extend(objectA, objectB), { a: 20, b: 2, c: 3, d: 40 });
assert.equal(extend(objectA, objectB), { a: 20, b: 2, c: 3, d: 40 });
6 changes: 2 additions & 4 deletions test/fixtures/xtend/case-1/result.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

const assert = require('assert');

const objectA = {
Expand All @@ -11,7 +12,4 @@ const objectB = {
d: 40,
};

assert.equal({
...objectA,
...objectB
}, { a: 20, b: 2, c: 3, d: 40 });
assert.equal({ ...objectA, ...objectB }, { a: 20, b: 2, c: 3, d: 40 });