views:

150

answers:

1

I came across this subject when I was reading through PrototypeJS's docs: its Identity Function. I did some further searching&reading on it and I think I understand its mathematical basis (e.g. multiplication by 1 is an identity function (or did I misinterpret this?)), but not why you would write a JS(or PHP or C or whatever)-function that basically takes X as a parameter and then just does something like return X.

Is there a deeper insight connected to this? Why does Prototype supply this function? What can I use it for?

Thanks :)

+3  A: 

Using the Identity function makes the library code slightly easier to read. Take the Enumerable#any method:

  any: function(iterator, context) {
    iterator = iterator || Prototype.K;
    var result = false;
    this.each(function(value, index) {
      if (result = !!iterator.call(context, value, index))
        throw $break;
    });
    return result;
  },

It allows you to check if any of the elements of an array are true in a boolean context. Like so:

$A([true, false, true]).any() == true

but it also allows you to process each of the elements before checking for true:

$A([1,2,3,4]).any(function(e) { return e > 2; }) == true

Now without the identity function you would have to write two versions of any function, one if you pre process and one if you dont.

  any_no_process: function(iterator, context) {
    var result = false;
    this.each(function(value, index) {
      if (value)
        throw $break;
    });
    return result;
  },

  any_process: function(iterator, context) {
    return this.map(iterator).any();
  },
derfred