Is there any good example of use cases for angular.identity()?

前端 未结 4 1787
一整个雨季
一整个雨季 2021-02-19 10:03

According to the documentation

A function that returns its first argument. This function is useful when writing code in the functional style.

I

4条回答
  •  心在旅途
    2021-02-19 10:26

    angular.identity is useful for cases where you want to reference an object bound to a parent by passing it from a parent to its children.

    An identity function is like the zero for functions. Kind of useless by itself, but occasionally useful as part of an expression using higher-order functions, where you can take a function as a parameter or return it as a result.

    Here is an example for array values:

    For example, you may bind a two-dimensional array to an initial selection, and then bind the contained inner arrays to each subselection. The values function in this case is the identity function: it is invoked for each group of child elements, being passed the data bound to the parent element, and returns this array of data.

    Use it when it is necessary to pass a dummy function to:

    • a promise ($q)
    • a compiler ($compile)
    • a unit test (spy/mock)

    which acts as a data source or pump for a pipe|filter.

    By comparison, Angular.noop incorrectly handles resolving/rejecting promises correctly because it always returns undefined, whereas Angular.identity correctly handles resolving/rejecting promises because it always returns the argument passed to it( f(x) = x ).

    In terms of constructors in Angular, it is relevant as such:

    JavaScript engines only return the instance of a constructor if the constructor does not explicitly return an object (i.e. a value of the type object or function). Hence new identity(value) is always an object. Thus new identity(value) == value only returns true if value is an object. This is because the equality operators in JavaScript always check for identity when one of the operands is an object.

    References

    • Purpose of an 'Identity Function'?

    • What is Angular.noop used for?

    • What is the practical use of the identity function in R?

    • What do people use the identity function for?

    • Use of the identity function in JavaScript

    • Where and why is identity function useful?

    • How do I pretty print an XSLT result document with removed source elements?

    • d3 wiki: Selections

    • AngularJS Issue #4579: orderBy filter doesn't support sorting by the value itself

    • Promises and the danger of angular.noop

    • The Identity Monad

    • Function composition and the identity function

    • Cocoa Drawing Guide: Transforms - The Identity Transform

    • Understanding Fluent APIs

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

    • https://softwareengineering.stackexchange.com/questions/256090/function-only-returns-unchanged-parameter-useless

提交回复
热议问题