Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

replace(): replace with 2 nodes? #38

Open
rstacruz opened this issue Jan 23, 2015 · 10 comments
Open

replace(): replace with 2 nodes? #38

rstacruz opened this issue Jan 23, 2015 · 10 comments

Comments

@rstacruz
Copy link

Would it be possible to replace a node with multiple statements? I understand this can't work on all places (only in bodys), but it'd be useful for some cases.

estraverse.replace(tree, {
  enter: function (node, parent) {
    if (/* something */) {
      return [
        { type: 'FunctionDeclaration', body: /* ... */ },
        { type: 'FunctionDeclaration', body: /* ... */ } ];
    }
  }
});

An example use case would be to to change a ForStatement (for (x;y;z){a}) into a WhileStatement (x; while (y) { z; a; }), which will be useful for js2coffee.

@goatslacker
Copy link

Came here to ask the same question. If it is possible it's undocumented.

@Constellation
Copy link
Member

Ah, currently, estraverse doesn't support it.

@exander77
Copy link

I second this feature.

@trusktr
Copy link

trusktr commented Jan 22, 2017

Just came looking for this too. A workaround is to run logic on the parent, replace the target child with the two children on the parent, then return the parent when you've traversed to that parent.

@WelaurS
Copy link

WelaurS commented May 26, 2019

Temporary fix:

return {
    type: esprima.Syntax.Program,
    body: bodyStatementsArray,
}

Will do pull request later

@sanex3339
Copy link
Contributor

+1

2 similar comments
@lwyj123
Copy link

lwyj123 commented Mar 20, 2020

+1

@rootgrandfather
Copy link

+1

@ptrcnull
Copy link

ptrcnull commented Feb 24, 2021

Dirty workaround that should work with BlockStatement:

estraverse.replace(tree, {
  enter: (node, parent) => {
    const nodes = // ...
    const index = parent.body.findIndex(n => n === node)
    parent.body.splice(index, 1, ...nodes)
  }
})

Using this instead of WelaurS' fix, because inserting a Program node inside a BlockStatement can mess up escodegen's formatting.

@wlbksy
Copy link

wlbksy commented May 10, 2021

Can we make ptrcnull's implementation into codebase ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests