what's-pure-function

what’s pure function ?

原文地址:what’s pure function?


Pure function

  1. arguments not change

    不修改传递给它们的参数

  2. always return the same set of arguments according to the arguments

    总是能根据传进来的参数返回对应唯一的结果

  3. it doesn’t mutate any data and it doesn’t have any side effects.

    对外部是没有影响的(网络请求、更新数据库等…),不会导致任何外部数据的变动

    如下 是计算一个产品价格和关税一起的费用的函数:

    function priceAfterTax(productPrice) {
     return (productPrice * 0.20) + productPrice;
    }

priceAfterTax()没有改变参数productPrice;满足(1)

返回一个新的结果,并且根据参数始终能保证相同的结果。即使几万次相同的输入,返回的结果也是相同的;满足(2)

对函数外的数据等没有任何影响;满足(3)

所以,这是一个Good Pure Function


Impure function

change the arguments. like network or database calls.

可以修改参数,进行网络请求、数据库操作等

比较一下两者

let tax = 20;
let val = 100;
function impureFunc(value){
   return (productPrice * tax / 100) + productPrice;
}

function pureFunc(value){
  return (productPrice * 0.20) + productPrice;
}

pureOutput = pureFunc(val);
impureOutput = impureFunc(val);

console.log("Impure result: " + impureOutput); // result is uncertain however input is same. 

console.log("Pure result: " + pureOutput); // result is consistent with same input

这里我们可以清晰地看到:impureFunc()违背了第(2)条规则,

因为tax是外部的,是会随时变动的,这就导致了返回结果对于同样的输入,有可能不唯一。


Why Using Pure Function ?

One of the major benefits of using pure functions is they are immediately testable. They will always produce the same result if you pass in the same arguments.

They also makes maintaining and refactoring code much easier.

使用纯函数最大的好处就是它们便于立刻测试,不需要书写玩整段代码,写完一个纯函数就可以马上测试。

因为根据第(2)条规则,纯函数总能根据传入参数返回相同的结果。

而这也使得代码在工程上整体变得易于维护和重构


注:函数式编程、Redux都需要使用pure function,作为根基,值得大家深入学习理解,

另外熟练使用纯函数和非纯函数混合开发编程,那就再好不过了。


参考:Difference between pure and impure function?

参考:JavaScript: What Are Pure Functions And Why Use Them?

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值