Skip to content

Commit

Permalink
Change to use spread syntax for shallow clones
Browse files Browse the repository at this point in the history
Closes GH-8.

Reviewed-by: Titus Wormer <[email protected]>
  • Loading branch information
remcohaszing authored Jul 19, 2023
1 parent 6c35b60 commit 6e422a2
Show file tree
Hide file tree
Showing 2 changed files with 177 additions and 234 deletions.
45 changes: 11 additions & 34 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -281,11 +281,9 @@ export function buildJsx(tree, options) {

/** @type {MemberExpression | Literal | Identifier} */
let name
/** @type {Array<Property>} */
let fields = []
/** @type {Array<Property | SpreadElement>} */
const fields = []
/** @type {Array<Expression>} */
const objects = []
/** @type {Array<Expression | SpreadElement>} */
let parameters = []
/** @type {Expression | undefined} */
let key
Expand Down Expand Up @@ -314,12 +312,12 @@ export function buildJsx(tree, options) {
const attribute = attributes[index]

if (attribute.type === 'JSXSpreadAttribute') {
if (fields.length > 0) {
objects.push({type: 'ObjectExpression', properties: fields})
fields = []
if (attribute.argument.type === 'ObjectExpression') {
fields.push(...attribute.argument.properties)
} else {
fields.push({type: 'SpreadElement', argument: attribute.argument})
}

objects.push(attribute.argument)
spread = true
} else {
const prop = toProperty(attribute)
Expand Down Expand Up @@ -373,33 +371,11 @@ export function buildJsx(tree, options) {
parameters = children
}

if (fields.length > 0) {
objects.push({type: 'ObjectExpression', properties: fields})
}

/** @type {Expression | undefined} */
let props
/** @type {MemberExpression | Literal | Identifier} */
let callee

if (objects.length > 1) {
// Don’t mutate the first object, shallow clone instead.
if (objects[0].type !== 'ObjectExpression') {
objects.unshift({type: 'ObjectExpression', properties: []})
}

props = {
type: 'CallExpression',
callee: toMemberExpression('Object.assign'),
arguments: objects,
optional: false
}
} else if (objects.length > 0) {
props = objects[0]
}

if (automatic) {
parameters.push(props || {type: 'ObjectExpression', properties: []})
parameters.push({type: 'ObjectExpression', properties: fields})

if (key) {
parameters.push(key)
Expand Down Expand Up @@ -470,9 +446,10 @@ export function buildJsx(tree, options) {
}
// Classic.
else {
// There are props or children.
if (props || parameters.length > 0) {
parameters.unshift(props || {type: 'Literal', value: null})
if (fields.length > 0) {
parameters.unshift({type: 'ObjectExpression', properties: fields})
} else if (parameters.length > 0) {
parameters.unshift({type: 'Literal', value: null})
}

callee = toMemberExpression(
Expand Down
Loading

0 comments on commit 6e422a2

Please sign in to comment.