nicoespeon / abracadabra

Automated refactorings for VS Code (JS & TS) ✨ It's magic ✨
https://marketplace.visualstudio.com/items?itemName=nicoespeon.abracadabra
MIT License
791 stars 48 forks source link

Convert dot.notation to square['brackets']['notation'] (and vice-versa) #104

Open martinandersen3d opened 4 years ago

martinandersen3d commented 4 years ago

Is this request related to a problem? Please describe.

I'm always frustrated when I need to convert this kind of formatting:

// property access
person.posts.members.count

into:

// indexer access
person['posts']['members']['count']

It might be necessary just like you convert a string into a template literal: you might need to turn it into an indexer access. The reverse is true.

Describe the solution you'd like

Example in Webstorm:

2020-09-03 Screenshot-kNgFfWTP

You can switch back & forth between the 2 syntaxes.

Help to implement

Comparing the 2 nodes in https://astexplorer.net/ you'll find the diff is in the MemberExpression node:

data.foo data.["foo"]
before
after

So it's a matter of conversion.

In terms of UX, we only want to change the property where the cursor is. Just like Webstorm example.

nicoespeon commented 4 years ago

Hey @martinandersen3d 👋

That's interesting, I never had to do this. Could you give me an example of when you need to switch to the square brackets notation? Is it a convention in your project?

dancrumb commented 1 year ago

I'll throw this observation into the mix: such a refactor would need to handle bracket notation that cannot be converted, such as:

object['with-dash']

That said, as @nicoespeon said, I can't think of an instance in my mumble, mumble years of engineering that I've needed this refactor pattern, so I would also be interested in hearing a use case.