简体   繁体   English

如何在不更新对函数的所有调用的情况下向纯函数添加新参数?

[英]How do you add a new argument to a pure function without having to update all calls to the function?

I make a pure function (example in js, but the question doesn't depend on the language) with one input argument and call it all over my application. 我用一个输入参数制作了一个纯函数(例如js中的示例,但问题不取决于语言),并在我的应用程序中全部调用它。

var day = 'Tuesday';
var doYouExist = function(you) {
    return !!you;
}

Then I realise that I should only check if you exist on Tuesdays so I decide to update the function... 然后我意识到我应该只检查星期二是否存在,所以我决定更新此功能...

var day = 'Tuesday';
var doYouExist = function(you) {
    if (day === 'Tuesday') {
      return !!you;
    }
}

But now it's not pure. 但是现在不纯净了。 I could add day as an argument, but the day variable isn't available in all of the places doYouExist() is called. 我可以将day添加为参数,但在所有调用doYouExist()的地方都不能使用day变量。

So my choices are either: 所以我的选择是:

  1. Use an impure function 使用不纯函数
  2. Inject 'day' to all of the places the function is called, then update the function and every call to that function to include a second argument. 将“ day”插入该函数调用的所有位置,然后更新该函数以及对该函数的每次调用以包含第二个参数。

Until now I've been using choice 1, but I don't know the recommended pattern (or any way to actually achieve what I want) for a functional approach. 到目前为止,我一直在使用选择1,但是我不知道功能性方法的推荐模式(或任何实际实现我想要的方式)。

如果day是一个常数,则您无需执行任何操作,因为您的函数仍然是纯函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM