-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(spread-assign): Add implementation
- Loading branch information
1 parent
70e1499
commit af6e6fd
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters