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

前端 未结 3 1317
不知归路
不知归路 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.

提交回复
热议问题