Metaduck

Some JavaScript Functional Sugar

I used to do a lot of Ruby, and now I’m doing only JavaScript. I really like Node and JavaScript, but since I’m lazy, I miss some of the niceties of the Ruby language. One of these niceties is that you can use a method reference when iterating over an Enumeration.

For instance, if you had a collection of User objects, you can extract all the name attributes by using:

users.map( &:name )

I recently realized that we can have a similar solution in JavaScript that I think is even more elegant:

function prop(propName) {
  return function(obj) {
    return obj [propName ];
  }
}

Now you can use this prop function as the property accessor shortcut:

users.map( prop('name') );

Hurray JavaScript!