Bringing Ruby fetch to the Javascript world

If you are a Rubyist you are probably comfortable using the fetch method on a day-to-day basis but when you are developing in Javascript this sweetness is not immediately available. This is why I wrote underscorejs-fetch.

The gist of the fetch method in Ruby is the following:

I wished I could find exactly the same in UnderscoreJS but _.has(), _.findKey() or are not quite what I am looking for.

So I went ahead and I implemented it myself. Here is how it works. If you have  an object and you want to fetch an existing property, you simply get it:

On the other hand if the property is not available, you get an Attribute not found error in return:

Now the sweetest part of fetch. When the property you are asking can't be found, you can simply pass a default:

Finally -- for sophisticated people -- you also have the option to pass a callback in case the key you are looking for is not found:

These example are also available as Jasmine specs in the Github repository. Running the specs is super-easy, just checkout the repository and run:

There is no reason to publish a 33 lines method function apart from sharing it and having the opportunity to discuss it with the community.

You love fetch? Then go fetch the repo on Github and tell me what you think!

Also published on Medium.

Leave a Reply

Your email address will not be published. Required fields are marked *

Answer the question * Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.