This article brings you the understanding of pure functions (code) in JavaScript functional programming. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
How to understand pure functions in functional programming?
Concept: It does not depend on the context of execution, nor does it affect the variables of the context. The output is only determined by the input
Understand the code
// 综上,非纯函数,输入依赖外部变量 let b = 1 function unPure(a) { return a + b } // 综上,非纯函数,输出改变外部变量 let o = {} function unPure(object) { object.ex = 1 return object } // 综上, 纯函数, 输出输入不影响外部变量 function pure(a) { let b = 1 return a + b }
I believe you have discovered that both the concept and code understanding are very simple, so why use pure functions? Below we list the benefits of using pure functions
Pure functions can be cached based on input
// 下面的代码我们可以发现相同的输入,再第二次调用的时候都是直接取的缓存 let squareNumber = memoize((x) => { return x*x; }); squareNumber(4); //=> 16 squareNumber(4); // 从缓存中读取输入值为 4 的结果 //=> 16 squareNumber(5); //=> 25 squareNumber(5); // 从缓存中读取输入值为 5 的结果 //=> 25
How to implement it? Let’s look at the following code
const memoize = (f) => { const cache = {}; return () => { var arg_str = JSON.stringify(arguments); // 关键就在这里,我们利用纯函数相同输入相同输出的逻辑,在这里利用cache做一个简单的缓存,当这个参数之前使用过时,我们立即返回结果就行 cache[arg_str] = cache[arg_str] || f.apply(f, arguments); return cache[arg_str]; }; };
Portability In the vernacular of sex, you can use it anywhere. If you have used it in project A, if you want to use it in project B, it will be ok.
Let’s understand the code again
// 我们注意看下方有两个注册的函数 // 不纯的, 如果B项目想要用到这个函数,很显然我们将其依赖的其它服务给搬过去 const signUp = function(attrs) { var user = saveUser(attrs); welcomeUser(user); } // 纯的, 我们再来看看下面这个纯函数写法,纯函数给了我们足够多的信息,我们想在B项目使用其功能只需将单个方法搬过去再给其注入需要的参数即可 const signUp = function(Db, Email, attrs) { return function() { var user = saveUser(Db, attrs); welcomeUser(Email, user); }; };
To sum up, this is very simple. We don’t need to care about other external information. We only need to give the function specific input and then assert its output
The above is the detailed content of Understanding pure functions in JavaScript functional programming (code). For more information, please follow other related articles on the PHP Chinese website!