preface
i believe that the word pure function has been heard by friends to some extent, and it is the basis of functional programming. this article mainly discusses pure functions, including basic concepts, advantages, classic cases of use, and how we should use them rationally in our daily life.
the concept of a pure function
first, let’s look at the basic concepts of pure functions:
the same input will always go to the same output, and there are no side effects during execution.
how do you understand the above concepts? we’re going to break the above sentence into two parts.
the same input always gets the same output.
let’s take a look at the following example:
let a = 1;
function xAdd(x) {
return x + a;
};
xAdd(1); //2
the above function is not a pure function, because in the process of our program execution, the variable is likely to change, and when the variable a changes, the output we get when we execute the same will be different.a
xAdd(1)
let’s look at another example:
function sum(x, y) {
return x + y;
};
sum(1,2); //3
in this example, conforming to the concept of the same input getting the same output is a pure function.sum
there are no side effects during execution.
here we need to figure out what side effects are, which here refer to external observable changes in the function during execution.
- INITIATE AN HTTP REQUEST
- MANIPULATE THE DOM
- modify external data
- console .log() print data
- Call Date.now() or Math.random()
the above series of operations can be called side effects. let’s take a look at an example of modifying external data to produce side effects:
let a = 1;
function func() {
a = 'b';
};
func();
console.log(a); // b
we run the function, the value of the external variable changes, which is what is called a side effect, so it is not a pure function. when we make modifications like this:func
a
func
function func2() {
let a = 1;
a = 'a';
return a
};
func(); // a
a function does not produce external observable changes to the pair, nor does it produce side effects, it is a pure function.fun2
a pure function, the two conditions mentioned above are indispensable.
benefits of pure functions
by understanding the concept of pure functions, i believe that some small partners can already feel some of the benefits of pure functions:
- it is easier to test, the results are only dependent on the input, and the output is stable when testing
- easier to maintain and refactor, we can write higher quality code
- it’s easier to call, and we don’t have to worry about any side effects of the function
- results can be cached because the same input always gets the same output
a classic example of the use of pure functions
since pure functions have so many benefits, let’s take a look at some of the classic examples of using pure functions.
the basic method of arrays
many of the basic methods of arrays are pure functions, such as ,,,, and so on.map
forEach
filter
reduce
reducers in redux
One of the three principles of Redux uses pure functions to perform modifications, including reducer to describe how an action changes the state tree.
Reducer is just some pure function that takes the previous state and action and returns the new state. –Redux
chinese documentation
Lodash
Lodash is a consistent, modular, high-performance JavaScript utility library. I believe that many small partners also often use it, which is also a pure function representative.
of course, there are many more, and here are not all examples, in general, pure functions are still very common.
how we use it wisely
in actual development, we can reasonably use pure functions to improve our development efficiency and code quality.
pure function components
we can create components in a purely functional way:
function Header(props) {
return <h2>{props.text}</h2>
}
Compare the way you create components using Class components:
class Header extends React.Component {
render() {
return <h1>{this.props.text}</h1>
}
}
we can summarize some of the advantages of pure function components:
- there are no side effects, and we don’t have to worry about some of the problems that side effects bring that are difficult to catch
- the syntax is more concise, readable, the amount of code is relatively small, and it is easy to reuse
- low memory footprint, no lifecycle and state management, improves performance
of course, pure function components also have their own disadvantages, for example: there is no life cycle.
the life cycle is sometimes indispensable, but fortunately now we have a good solution – react-hooks. with the hooks function, we can use methods such as equivalent to life cycle, state management, etc. in the function components.
write public methods with reasonable use of pure functions
when writing public methods, we try to write with pure functions.
suppose we want to write a common method that converts lowercase letters in an array to uppercase letters:
let lists = ["q","w","e"];
let upperCaseLists = () => {
let arr = [];
for (let i=0, length= lists.length; i<length; i++) {
let item = lists[i];
arr.push(item.toUpperCase());
}
lists = arr;
}
although the above function can achieve logical multiplexing, it has side effects and is certainly not suitable for public methods, so we want to optimize it:
let upperCaseLists = (value) => {
let arr = [];
for (let i=0, length= value.length; i<length; i++) {
let item = value[i];
arr.push(item.toUpperCase());
}
return arr;
}
optimize with better readability:forEach
let upperCaseLists = (value) => {
let arr = [];
value.forEach((item) => {
arr.push(item.toUpperCase());
})
return arr;
}
continue with the map for further optimization:
let upperCaseLists = (value) => {
return value.map((item) => item.toUpperCase())
}
isn’t that concise? how to optimize the specific method should be based on the actual situation and business needs.