With JavaScript 1.6 we have the Array.map method to map a function to
each element in an array, and Prototype itself has invoke and pluck.
But what if you want to map a function to a set of parallel arrays,
where the elements in each array correspond to the arguments of the
function?  It's a common higher-order function, though not implemented
in a lot of languages.  I think it naturally fits in the Function
prototype.  Here's a suggested implementation:

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;
  }
});

Note, it's not great for sparse arrays, and if such are provided as
arguments, the function mapped needs to be tolerant of undefined
inputs.  But it would be pretty easy to wrap a function so as to
handle such inputs.  Dealing well with very sparse arrays would slow
the typical case down too much to be worthwhile.

Any comments or suggestions for improvement?

Titi


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Prototype: Core" group.
To post to this group, send email to prototype-core@googlegroups.com
To unsubscribe from this group, send email to 
prototype-core-unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/prototype-core?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to