Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

According to the documentation

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

I am wondering where I can find a good example of such use case - writing code in functional style in an angular app. Thanks

like image 691
KailuoWang Avatar asked Mar 14 '13 22:03

KailuoWang


People also ask

What is the identity function used for?

Identity functions are mostly used to return the exact value of the arguments unchanged in a function. An identity function should not be confused with either a null function or an empty function. Here are the important properties of an identity function: The identity function is a real-valued linear function.

What is angular identity?

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

What is identity function JavaScript?

An Identity function is a function that does nothing. It just returns what it receives. It's like the number zero, it's just there to fill the place without doing anything, and sometimes that is exactly what is needed. So let's try to write an identity function in JavaScript.


2 Answers

Example from the AngularJS source code:

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

Explanation:

In case transformationFn is provided as first parameter, it will be called with value as it's own parameter. Otherwise identity function will be called with the same value.

As ng source code mentions:

This function is useful when writing code in the functional style.

What this means is that in functional programming there are no globals, so you always have to pass/inject in everything you need.

like image 53
Stewie Avatar answered Sep 17 '22 20:09

Stewie


Lets say we have these two below functions:

$scope.square = function(n) {
return n * n
};


$scope.multplybyTwo = function(n) {
return n * 2
};

To call this in a functional way:

$scope.givemeResult = function(fn, val) {
return (fn || angular.identity)(val);
};

Then You may use the above function something like below:

$scope.initVal = 5;
$scope.squareResult = $scope.givemeResult($scope.square, $scope.initVal);
$scope.intoTwo = $scope.givemeResult($scope.multplybyTwo, $scope.initVal);

You may follow the below link:

http://litutech.blogspot.in/2014/02/angularidentity-example.html

like image 31
Asutosh Avatar answered Sep 17 '22 20:09

Asutosh