facebook/idx

Compare this with Lodash.get

Closed this issue · 5 comments

Hi,
Could you let me know? What is different between this plugin with Lodash.get?
https://lodash.com/docs/#get

Thanks

@williamtran29 The are indeed very similar. Here are the differences that I can come up with (having never used _.get before):

  • _.get returns undefined for unresolved values, whereas idx preserves null where applicable.
  • _.get supports a default value, whereas idx does not. This is because idx is an intermediate solution until an operator is added to ECMAScript (which does not currently propose a default value mechanism).
  • idx ships with a Flow definition for type safety (e.g. so that the return type is preserved and so that you can access properties on a nullable object, but only if those properties are otherwise valid on the object).
  • babel-plugin-idx allows stripping most of the runtime performance implications of the function invocation and intermediate value checks.

I hope this is helpful. Thanks for the question!

_.get supports a default value, whereas idx does not.

I think this is a non-issue as you can just do idx(foo, x => x.bar.baz) || defaultValue, which also ensures the default value is lazily computed if it's something expensive (imagine something like (idx(foo, x => x.bar.baz) || someExpensiveFunction())

one thing to keep in mind about the default value (3rd parameter) to lodash.get is that it's only used if the expression evaluates to undefined, if it's null the default value will not be used, which is not what i want 99% of the time.

anyone migrating from lodash.get to idx may find this codemod that i wrote useful https://github.com/brettjashford/codemods

@brettjashford For what it's worth, the optional chaining proposal just reached stage 3 recently, so in the near future I think that'll totally replace idx.

// Old
idx(foo, x => x.bar.baz)

// New
x?.bar?.baz

Babel supports it, and TypeScript support is coming.

However, do note that there's subtle differences between _.get, idx and optional chanining around handling of null and undefined, so definitely test thoroughly when converting between them. For example, idx(foo, x => x.bar.baz) will return null if x.bar is null or undefined if x.bar is undefined, whereas the optional chaining operator will return undefined in both cases.

interesting, thanks for pointing that out!

i'm eagerly awaiting typescript 3.7 with optional chaining support. planning to write an idx -> optional chaining codemod then, although it probably won't take into account the null vs undefined differences you mentioned.