使用js reduce方法。只是风格问题?

using js reduce method. just a matter of style?

我正在使用 js 并试图决定我的代码的风格。

我需要找出人物集合中最年轻的人的年龄。我的问题是:如果数组为空,我应该 return undefined 吗?如果数组为空,我应该让它失败吗?

这是我所做的:


let people = [{name: "a", age: 20}, {name: "b", age: 21}]

function nameOfYoungestPerson(people) {

    let yst = youngest(people)
    
    return yst && yst.name

}

function youngest(people) {

    return people.reduce((yst, person) => yst === undefined ? person : 
               (person.age < yst.age ? person : yst), undefined)
}

另一种选择是让它失败:


function youngest(people) {
    return people.reduce((yst, person) => person.age < yst.age ? person : yst) 
}


还有,哪个更好:


function youngest(people) {

    return people.reduce((yst, person) => yst === undefined ? person : 
               (person.age < yst.age ? person : yst), undefined)
}


或:


function youngest(people) {

    return empty(people) ? undefined : people.reduce((yst, person) => 
                                              person.age < yst.age ? person : yst)

}

让它失败吧。确保参数有效是调用者的责任,如果参数无效,最好尽快让调用者知道。如果您 return 未定义,调用者将保持 运行 并且一旦您实际尝试使用未定义的值执行某些操作,您的程序将在很晚之后失败。到那时,您可能很难弄清楚未定义值的来源。

当然能写一个不会崩溃的函数就更好了。然而问题在于,如果数组为空,则实际上没有任何有用的值可以return。 null 和 undefined 可能只会将崩溃推迟到以后。当然,除非调用者检查未定义的 return 值,但是与仅让调用者检查数组是否为非空相比有什么优势呢?没有。

在您展示的两个变体中,第二个更好,因为每个循环迭代只会评估一个条件。第一个将在每次迭代中评估两个条件,从而降低效率。

我不会“让它失败”,但如果你 100% 知道阵列中总会有人,你 可能 不会为它构建案例.

虽然添加一种处理空数组的方式非常简单,但我可能会这样做。我建议不要 returning undefined,因为这会导致混淆,而是 return null,因为如果对象上不存在该名称,它也可能 return undefined,这会导致意外行为。

关于如何设置样式的问题,我建议您在单独的一行中处理空案例,因为您那里的单行解决方案非常长且难以快速阅读恕我直言。

function youngest(people) {
    if (!people.length) return null;
    return people.reduce((yst, person) => person.age < yst.age ? person : yst) 
}