Rules
- no side effects (function can't rely on anything not provided to it)
- inputs and outputs
In Practice
- Nested functions are always an indication of complexity
Creates Functions that are
- Easy to read
- Easy to reuse
- Easy to test
- Easy to change
Examples (all pulled from code I reviewed at PaperG just simplified and anonymized):
Pure vs Impure
// pure functions have no side effects
// the results are predictable and consistent
function square (num) {
return num * num;
}
// pure functions do not mutate their agruments
function squareAll (nums) {
return nums.map(square);
}
// impure function that mutates arguments
function badSquareAll (nums) {
for (var i = 0; i < nums.length; i++) {
nums[i] = square(nums[i])
}
}
Reusability
// add foo to bar
var foo = 1;
var bar = 2;
function add (number_1) {
return number_1 + bar;
}
// add foo to bar
var foo = 1;
var bar = 2;
function add (number_1, number_2) {
return number_1 + number_2;
}
Testability
var foo = [1, 2, 3, 4, 5];
_.each(function (num) {
num++;
});
var foo = [1, 2, 3, 4, 5];
function add_one (num) {
return num + 1;
}
var bar = foo.map(add_one);
$scope.toggleView = function($event, grid) {
if (grid) {
stopCropping();
}
setGrid(grid);
$event.stopPropagation();
};
function toggleView ($event, grid) {
// not entirely sure how this code works but....
var newView = _.cloneDeep(oldview);