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

前端 未结 4 1788
一整个雨季
一整个雨季 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:09

    Correct me if I'm wrong, but my understanding is that this

    function transformer(transformationFn, value) {
      return (transformationFn || angular.identity)(value);
    };
    

    could be "un-refactored" to this

    function transformer(transformationFn, value) {
      if (transformationFn) {
        return transformationFn(value);
      } else {
        return angular.identity(value);
      }
    };
    

    which would be functionally equivalent to this identity-less version:

    function transformer(transformationFn, value) {
      if (transformationFn) {
        return transformationFn(value);
      } else {
        return value;
      }
    };
    

    So I guess the use case would be when you want to apply a certain transformation to a value when you're supplied with something that may or may not actually exist.

    I wanted to better explain the identity function (as I understand it), although as I review my answer I don't think I really answered your question. Leaving my answer here anyway in case it's helpful.

提交回复
热议问题