JavaScript Higher-order Programming: Beyond Array.map

In developing the filters for the datepicker widget, I came upon a situation where I wanted to get an element-wise OR of two Boolean arrays, i.e. produce an array where each element is the reslt of OR-ing the corresponding values of two other arrays. To get the code out the door I did a brute-force iteration over the array, but what I really wanted was an implementation of the standard higher-order "map" function that could handle multiple parallel arrays. As of Javascript 1.6, the Array object has a map method, but that only works for one array. It seems like the multi-array version would be a natural extension to the Function object. So here is my Prototype-style extension:

Object.extend(Function.prototype, {
map: function() {
if (!arguments.length) return null; // Nothin' in, nothin' out
var args = $A(arguments);
var __this = args.shift();
var maxLength = 0;
args.each(function(arr) {
maxLength = (maxLength >= arr.length) ? maxLength : arr.length;
});
var results = new Array();
for (var i = 0; i < maxLength; ++i) {
results[i] = this.apply(__this, args.pluck(i));
}
return results;
}
});

So back to my problem of an element-wise or:

var result array = (function(a,b) {return a||b;}).map(null,array1,array2);

If there is enough demand for Prototype-less JavaScript version, I would be happy to oblige. But my hope is to get something of this sort included in the Prototype core.

Trackback URL for this post:

http://www.tigretigre.com/trackback/8