繁体   English   中英

从函数返回还是传入函数?

[英]Return from function or pass into function?

处理这些数据的更好方法是什么? 这只是个人喜好问题吗? Guessing 2 不太容易意外修改 monday...friday 数组,并且这一层的代码更少。 是否有最佳实践方法? 有性能差异吗?

  1. 像这样?
        // Arrays to hold what stock price belongs to what day of the week - Note these arrays are used some way down the line
        var monday = [], tuesday = [], wednesday = [], thursday = [], friday = []

        // Sort each stock date into a day of the week
        FindDayFromDate(historyData, monday, tuesday, wednesday, thursday, friday);

        // Find the average price for each day of the week
        const avgPrices = FindAveragePricePerDay(monday, tuesday, wednesday, thursday, friday);
  1. 像这样?
        // Sort each stock date into a day of the week - sortedDays contains arrays of monday...friday
        const sortedDays = FindDayFromDate(historyData);

        // Find the average price for each day of the week - Expand sortedDays inside function to access monday...friday
        const avgPrices = FindAveragePricePerDay(sortedDays);

一个好的函数应该永远没有副作用。 它应该是纯粹的,一次只做一项特定的工作。 作为软件程序员/开发人员,我们必须编写基于输入实际产生输出的源代码。 这种强大的纯函数实际上避免了各种副作用和代码异味。 让我们看几个例子来理解这一点。

假设我们有一个名为Greeting的函数,如下所示

function Greeting(name) {
  return `Hello ${name}`;
}

它是纯粹的,因为您将始终得到输出Hello {name}为通过参数传递的名称 让我们看一下具有许多副作用的相同功能的另一个版本。

var greeting = "Hey";

function Greeting(name) {
  return `${greeting} ${name}`;
}

现在,这个函数并不纯粹。 猜猜为什么 ? 因为我们不确定我们会收到什么输出,因为函数实际上依赖于名为greeting的外部变量。 因此,如果有人将变量greeting的值更改为其他值,让我们说Hello ,那么显然函数的输出将会改变。 因此,该函数现在与外部变量紧密耦合。 这就是为什么它不再是纯函数了。

所以总而言之,你必须以一种没有依赖性和副作用的方式编写你的函数,并且它总是可以完成一项工作。

这是最好的做法:)

快乐编码:)

我相信第二个函数“FindAveragePricePerDay”调用可以调整为单日执行,以便在其他地方重复使用

    const avgPrices = sortedDays.map(day => FindAveragePricePerDay(day));
    /* you can also simplify the FindAveragePricePerDay using the reduce method
     following this parameters array.reduce(function(total, currentValue, currentIndex, arr), initialValue) 
so all the second line would be */
    const avgPrices = day.reduce((t,c,i,arr) => t + c/arr.length, 0);

有关 array.reduce 的更多信息,请查看

暂无
暂无

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

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