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. The gist of its usage is the following:

    item = { name: 'pen', color: 'blue' }
    item.fetch(:name)                                     #=> 'pen'

    item.fetch(:price)                                    #=> key not found error
    item.fetch(:price, '2$')                              #=> '2$'
    item.fetch(:price) { |key| "the #{key.to_s} is 2$"}   #=> "the price is 2$"

But when you are developing in Javascript this sweetness is not immediately available. I had a look at UnderscoreJS but I couldn’t find anything similar. _.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:

    var item = { name: 'pen', color: 'blue' };
    _.fetch(item, 'name'); //=> pen

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

    var item = { name: 'pen', color: 'blue' };
    _.fetch(item, 'price'); //=> Error('Attribute not found');

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

    var item = { name: 'pen', color: 'blue' };
    _.fetch(item, 'price', '2$'); //=> '2$'

Finally if you are a of sophisticated person you also have the option to pass a callback to determine the default value ending up with something like this:

    var item = { name: 'pen', color: 'blue' };
    _.fetch(item, 'price', function(key) { 
      return "The " + key + " cannot be found"; 
    //=> 'The price cannot be 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:

    sudo npm install -g grunt-cli
    npm install
    grunt jasmine

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!

photo of Alfredo Motta

Software Engineer
comments powered by Disqus