Skip to content

Updating setter function's parameter cause invalid output #567

Open
@pionxzh

Description

Adding/removing any parameter in an object's setter function generates wrong output.

Transform

export default function transformer(file, api) {
  const j = api.jscodeshift;

  return j(file.source)
    .find(j.FunctionExpression)
    .forEach(path => {
      path.node.params.push(j.identifier('test'))
    })
    .toSource();
}

Input

const obj = {
    set field (num) {}
};

Expected Output

const obj = {
    set field (num, test) {}
};

Actual Output

const obj = {
    set field function(num, test) {}
};

path.node.params.splice(0) can also trigger the error.

It can be verified on astexplorer.

Hot Fix

You can manually fix it by recreating the Property

if (j.Property.check(path.parentPath.node)) {
    const newProperty = j.property(
        path.parentPath.node.kind,
        path.parentPath.node.key,
        j.functionExpression(
            path.node.id,
            path.node.params,
            path.node.body,
            path.node.generator,
            path.node.expression,
        ),
    )

    path.parentPath.replace(newProperty)
}

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions