Monday, September 13, 2010

Hey, you got Ruby in my JavaScript!

I am a big fan of Ruby's Enumerable module. I has some crazy useful methods that get mixed into every array. I have said before that I wish I could somehow use Ruby's Enumerable module in every other language I use. I don't know about every other language I use, but if we're talking about JavaScript, it's pretty doable.

For example, let's look at the find_all method from Enumerable. According to the documentation, when called on an object enum and passed a block block, it returns an array containing all elements of enum for which block is not false. The following line will give us the integers from 1 to 10 that are divisible by 3:

(1..10).find_all {|i|  i % 3 == 0 }   #=> [3, 6, 9]

It's like a little query engine on your arrays. Don't you wish we could do this in JavaScript? Something like this:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].findAll(
  function(x) {
    return x % 3 === 0;
)  //=> [3, 6, 9]

Well, one very nice thing about JavaScript is that we can add methods to any object's prototype, and then any object of that type will have that method on it. In our case, we can add a findAll method to all Array objects. To make this work, all we have to do is execute this first:

Array.prototype.findAll = function(f) {
  var result = [];
  for (var i = 0; i < this.length; i += 1) {
    if (f(this[i])) {
  return result;

Give it a try. Hey, you got Ruby in my JavaScript! Okay, to be fair, we can't really give Ruby the credit. It's just an example of higher-order function usage, but it enables me to give JavaScript a feature that Ruby has spoiled me with.


No comments:

Post a Comment