It’s just data

Ruby2js += underscore.js

When compared to Ruby, JavaScript doesn’t have as much functional support built in.  Underscore.js fills that gap for many.  Underscore.js, in turn, was inspired by Ruby’s Enumerable module.  A underscore filter (tests) completes the mapping.

In many cases, the resulting JavaScript is formed by applying a number of filter rules.  For example, starting with:


This is first expanded to use Array.prototype.slice to ensure the update happens in place:

a.splice(0, a.length, *a.flatten())

Next, the method call is rewritten to use the underscore flatten function:

a.splice(0, a.length, *_.flatten(a))

Finally, as JavaScript doesn’t have a splat operator, the call is rewritten using Function.prototype.apply:

a.splice.apply(a, [0, a.length].concat(_.flatten(a)))

Tim Bray will be pleased to hear that Ruby2js currently maps a.sort() to

_.sortBy(a, _.identity)

Add your comment