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
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.
A function that returns its first argument. This function is useful when writing code in the functional style.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With