preface

The term pure function, which I’m sure you’ve all heard of at some point, is the foundation of functional programming. This paper mainly discusses the pure function, including the basic concept, advantages, classic cases and how to use it reasonably in our daily life.

The concept of pure functions

First let’s look at the basic concepts of pure functions:

The same input always leads to the same output without any side effects during execution.

How to understand the above concept? Let’s break the above sentence into two parts.

Same input, always get the same output.

Take a look at the following example:

let a = 1;

function xAdd(x) {
    return x + a;
};
xAdd(1); / / 2
Copy the code

The above function is not a pure function, because variable A may change during the execution of our program, and when variable A changes, we also get a different output when we execute xAdd(1).

Here’s another example:

function sum(x, y) {
    return x + y;
};
sum(1.2); / / 3
Copy the code

In this example, where the same input gives the same output,sum is a pure function.

There are no side effects during execution.

Here we need to be clear about what a side effect is, and a side effect is an external observable change that occurs during the execution of a function.

  1. Making an HTTP request
  2. Operating the DOM
  3. Modifying external Data
  4. Console.log () prints data
  5. Call date.now () or math.random ()

All of these actions can be called side effects. Here is an example of modifying external data to create side effects:

let a = 1;
function func() {
    a = 'b';
};
func();
console.log(a); // b
Copy the code

We run the func function, and the value of the external variable A changes, which is called the side effect, so func is not a pure function. When we modify it like this:

function func2() {
    let a = 1;
    a = 'a';
    return a
};
func(); // a
Copy the code

Function fun2 has no external observable changes and therefore no side effects; it is a pure function.

For a pure function, both conditions are necessary.

The benefits of pure functions

By understanding the concept of pure functions, I believe that some partners have been able to feel some benefits of pure functions:

  • Easier to test, the results rely only on the input, when testing to ensure that the output is stable
  • It’s easier to maintain and refactor, and we can write higher-quality code
  • It’s easier to call, and we don’t have to worry about the side effects of the function, right
  • The results can be cached because the same input always results in the same output

A classic case of pure functions

Since pure functions have so many advantages, let’s take a look at some classic cases of pure functions.

The basic methods of arrays

Many basic methods of array is pure functions, such as map, forEach, filter, reduce and so on.

Redux of the reducer

One of the three principles in Redux uses pure functions to perform modifications, and Reducer is used to describe how actions change the state tree.

Reducer is just pure functions that receive the previous state and action and return the new state. –Redux

Chinese document

Lodash

Lodash is a consistent, modular, high-performance JavaScript utility library. I’m sure many of you use this a lot, but this is also a pure function representation.

Of course, there are many more, and I’m not going to give you any examples, but in general, pure functions are pretty common.

How can we use it wisely

In the actual development, we can reasonably use pure function to improve our development efficiency and code quality.

Purely functional component

We can create components as pure functions:

function Header(props) {
    return <h2>{props.text}</h2>
}
Copy the code

Compare this to creating a component using a Class component:

class Header extends React.Component {
  render() {
    return <h1>{this.props.text}</h1>
  }
}
Copy the code

We can summarize some advantages of purely functional components:

  • No side effects, we do not have to worry about side effects brought by some difficult to capture the problem
  • The syntax is more concise, readable, the code is relatively small, easy to reuse
  • Small memory footprint, no life cycle and state management, improved performance

Of course, pure functional components have their own disadvantages, such as no life cycle.

Life cycles are sometimes necessary, but we now have a good solution — react-hooks. Using the hooks function, we can use methods equivalent to life cycle, state management, and so on in function components.

Use pure functions to write common methods

When writing public methods, we try to write them as pure functions.

Suppose we want to write a public method that converts a lowercase letter in an array to an uppercase letter:

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;
}
Copy the code

This function can be used for logic reuse, but it has side effects and is definitely not suitable for public methods, so we need 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;
}
Copy the code

Optimize with a more readable forEach:

let upperCaseLists = (value) = > {
    let arr = [];
    value.forEach((item) = > {
        arr.push(item.toUpperCase());
    })
    return arr;
}
Copy the code

Continue with map for further optimization:

let upperCaseLists = (value) = > {
    return value.map((item) = > item.toUpperCase())
}
Copy the code

Isn’t that neat? How to optimize the specific method should be based on the actual situation and business needs.

reference

Segmentfault.com/a/119000000…

Cuggz.blog.csdn.net/article/det…

www.redux.org.cn/

The last

The concept of a pure function is actually not complicated, and we must have encountered it in our work before we had a thorough understanding of it. Only to use it reasonably, is the development of a weapon.