villesau / optional-chaining-codemod

Codemod to migrate from Lodash get and logical and expressions to optional chaining
MIT License
112 stars 14 forks source link

Doesn't handle curried versions of `get()` and `getOr()` #24

Open daveisfera opened 4 years ago

daveisfera commented 4 years ago

One last big thanks for the awesome codemod!

Curried versions of get() and getOr() cause an error:

TypeError: Cannot read property 'type' of undefined
    at skip (/Users/dlj/projects/optional-chaining-codemod/transform.js:82:35)
    at NodePath.<anonymous> (/Users/dlj/projects/optional-chaining-codemod/transform.js:133:9)
    at NodePath.<anonymous> (/usr/local/lib/node_modules/jscodeshift/src/collections/Node.js:142:47)
    at /usr/local/lib/node_modules/jscodeshift/src/Collection.js:75:36
    at Array.forEach (<anonymous>)
    at Collection.forEach (/usr/local/lib/node_modules/jscodeshift/src/Collection.js:74:18)
    at Collection.replaceWith (/usr/local/lib/node_modules/jscodeshift/src/collections/Node.js:140:17)
    at Collection.replaceWith (/usr/local/lib/node_modules/jscodeshift/src/Collection.js:413:43)
    at mangleLodashGets (/Users/dlj/projects/optional-chaining-codemod/transform.js:132:8)
    at module.exports (/Users/dlj/projects/optional-chaining-codemod/transform.js:313:3)

But they could be turned into fat arrow functions using the existing logic, like the following: get('value') to v => v?.value getOr(default, 'value') to v => v?.value ?? default

villesau commented 4 years ago

Can you give a bit more complete example with imports and such? Does Lodash provide curried versions of functions out of the box? It might be hard to track wether the function is curried or not and what to do and when.

daveisfera commented 4 years ago

Something like this

const a = [{ bogus: true }, { count: 100 }, { missing: true }];

const b = flow([
    filter(get('count')),
    get([0, 'count']),
])(a);

Could be changed to:

const b = flow([
    filter(v => v?.count),
    v => v?.[0]?.count,
])(a);
daveisfera commented 4 years ago

Also, the number of arguments should be an indication of it being curried (i.e. 2 arguments to get() is a "standard call" and 1 argument to get() is a "curried call")