Please explain usage of _.identity(value) of underscore.js

前端 未结 3 1316
不知归路
不知归路 2021-01-17 08:05

Please explain usage of _.identity(value) of underscore.js. Not able to understand it from the documentation ( http://underscorejs.org/#identity ).

Can

相关标签:
3条回答
  • 2021-01-17 08:10

    A JavaScript code pattern involving identity is filtering values based on truthiness, e.g.

    var a = [null, null, [1,2,3], null, [10, 12], null];
    
    a.filter(_.identity) 
    

    yields [Array[3], Array[2]].

    Using

    _.compact(a)
    

    is clearer, but one may not use lodash or underscore at all, e.g.

    function identity(x) { 
       return x; 
    }
    
    a.filter(identity)
    

    Whether it is a good code pattern is questionable for several reasons, but it's being used in the wild.

    It is not a NOOP at all. A NOOP is an imperative construct in e.g. assembly, whereas in functional programming, it is like other functions in that it returns a value. If identity were a NOOP, then all pure functions could also be considered noop, and it would not be a sensible thing.

    0 讨论(0)
  • 2021-01-17 08:14

    It's essentially a no-operation function. It returns the value of whatever was passed into it.

    The part about it being used as a "default iterator" within the library itself means that in other functions which may have an optional "iterator" parameter (which is likely used as a function to apply to each element of an array of some kind), if no iterator parameter is passed, the library will use this "no-op" iterator instead and the elements of the array will remain unchanged.

    0 讨论(0)
  • 2021-01-17 08:14

    A specific example:

    Underscore.js defines _.each and as like this.

    _.each = function(obj, iterator, context) {
      ...
    }
    

    This iterator shows el value. You maybe have used this idiom.

    _.each([1, 2, 3], function(el){
      console.log(el);
    });
    

    This iterator returns el value without change.

    _.each([1, 2, 3], function(el){
      return el;
    });
    

    The function that returns a value without change occur frequently. So Underscore.js wants to define the function. Underscore.js names the function _.identity.

    _.identity = function(value) {
      return value;
    };
    

    If Underscore.js wants to use a default iterator, all Underscore.js need is call _.identity.

    _.each([1, 2, 3], _.identity);
    
    0 讨论(0)
提交回复
热议问题