dsfields / elv

Elvis operator functionality for JavaScript.
MIT License
7 stars 0 forks source link

tryGet for objects #3

Closed electic closed 5 years ago

electic commented 5 years ago

I noticed that you have tryGet for arrays which I think is awesome. But is there something for objects? For example

this.object.attribute

However, if for some reason, the object is null then you get an error. Is there a way to check the chain to see if it is all valid?

dsfields commented 5 years ago

I've been resisting the urge to write a tryGet() function for properties on an object. It can be useful, but there's no way to make this type of functionality reasonably performant. I could see something like this:

// set val to 42 or obj.foo.bar.baz if it is defined
const val = elv.tryGet(obj, 'foo.bar.baz', 42);

We end up requiring string parsing to access properties. We can speed it up by caching access strategies. Even though it's considerably more verbose to write out the straight JavaScript, it's still orders of magnitude faster from a performance perspective.

I'd consider adding the feature with a suggestion that it not be used in hot code paths. However, I'm debating whether or not it's worth it at this point considering optional chaining is now in stage 3.

electic commented 5 years ago

Good point, I had no idea optional staging was in stage 3. In that case, you are right. I don't think there is a point adding it. Thanks again!