JasonWyatt

This blog is full of stuff, and things.

Find my resume.

permalink

Creating a Ruby-style each() for JavaScript

Yep, this is another post that modifies built-in prototypes for JavaScript to add functionality I wish was already there.

I’ve been learning Ruby lately and I’ve really fallen in love with the idea of “blocks” and the way they’re used in that language. I thought it could be useful to introduce some of the functions that use blocks from Ruby into JavaScript using function objects.

This code adds a .each() function to every object in the runtime:

Object.prototype.each = function(fn){
    var scope = arguments.length > 1 ? arguments[1] : window;
    for(var i in this){
        if(this[i] instanceof Function)
            continue;
        if(fn.call(scope, this[i], i) == false)
            break;
    }
    return this;
};

Let’s walk through what’s going on here:

  1. Give all objects a new function called “each” by giving Object.prototype a new function called “each”. Let each accepts at least one argument: fn, a function object.
  2. If more than one argument was specified, define the second argument to be the scope within which we’ll call the function. Otherwise, set the scope to the window object.
  3. Iterate through every member of this, the object on which each() was invoked:
    1. Skip the member if it’s a function object itself (we only want to iterate over non-functions).
    2. Call the function within the defined scope and with two parameters: the member itself, and it’s identifier.
    3. If the function returns false, interpret this as a signal to stop iterating.
  4. Return the object on which each() was invoked, to support function chaining.

What are some other features you’ve created “translations” for a language based on another language?

blog comments powered by Disqus