Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

A Small Example of the Convenience of Currying

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.

Quick Summary of Lodash's Get:

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!

Using accessor

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')

Getting to the point

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").

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment