A while back I made a helper function:
export const accessor = (obj, defaultValue = null) => x => _.get(obj, x, defaultValue);
Pretty straightforward. It's just a function which creates a custom version of lodash's get for a specific object. Great for react.
Instead of doing something like this all the time:
isObject(this.state.house) && isObject(this.state.house.address) && this.state.house.address.zipcode
I can do this
_.get(this.state.house, 'address.zipcode', null)
Nice!
Let's say you access an object house
a lot. You could use accessor
like so:
const house = accessor(this.state.house);
house('address.zipcode')
Ok, so I had my accessor. Happily using it.
Oh, I need to use lodash's get
for some one time thing.
Oh, I haven't imported get
—looks like I've only imported my helper function, "accessor", in this file I'm working in.
Meh. I'll just use it instead.
accessor(this.state)('house.address.zipcode');
Hmmm. You know what.. That's not bad at all.
I get the get
functionality like I normally would, with syntax func(...)(...)
that reads pretty cleanly.
I still get the convenience of being able to make a custom accessor (like const house
above).
And, I can do all this using only one function ("accessor") instead of two ("accessor" and "_.get").