Skip to content

Commit

Permalink
feat(spread-assign): Add implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
ticklepoke committed Jul 9, 2021
1 parent 70e1499 commit af6e6fd
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/convert-spread-assign.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { namedTypes } from 'ast-types';
import { API, FileInfo, Options } from 'jscodeshift';

type ObjectProperties =
| namedTypes.SpreadElement
| namedTypes.ObjectProperty
| namedTypes.Property
| namedTypes.ObjectMethod
| namedTypes.SpreadProperty;

export default function transform(file: FileInfo, api: API, options: Options): string {
const j = api.jscodeshift;

return j(file.source)
.find(j.ObjectExpression)
.filter((path) => path.value.properties.some(({ type }) => type === 'SpreadElement'))
.forEach((path) => {
// create array of
const { properties } = path.value;
let queue: ObjectProperties[] = [];
const objectAssign = j.callExpression(j.memberExpression(j.identifier('Object'), j.identifier('assign')), [
j.objectExpression([]),
]);
for (const property of properties) {
if (property.type === 'SpreadElement') {
if (queue.length > 0) {
const objectExpression = j.objectExpression(queue);
objectAssign.arguments.push(objectExpression);
}
if (property.argument.type === 'Identifier') {
objectAssign.arguments.push(j.identifier(property.argument.name));
} else if (property.argument.type === 'ObjectExpression') {
objectAssign.arguments.push(j.objectExpression(property.argument.properties));
}
queue = [];
} else {
queue.push(property);
}
}
if (queue.length > 0) {
const objectExpression = j.objectExpression(queue);
objectAssign.arguments.push(objectExpression);
}
j(path).replaceWith(objectAssign);
})
.toSource(options);
}
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ const TRANSFORMS = [
value: 'remove-debugger',
},
// YARN PLOP TRANSFORMS
{
name: 'Convert object spread patterns to Object.assign()',
value: 'convert-spread-assign',
},
{
name: 'Convert then() promises to async / await',
value: 'convert-then-async',
Expand Down

0 comments on commit af6e6fd

Please sign in to comment.