javascript - Eloquent JS 第 5 章中的这段代码做了什么?

标签 javascript recursion

我很难理解代码的第一部分。我不明白我们要用 combine 函数做什么。还有 thisOneCounts 是做什么的?真的,任何我没有评论过的东西我都不明白。

//count the ancestors over 70
function countAncestors(person, test) {
    //supposed to combine parents recursively
    function combine(person, fromMother, fromFather) {
        //stores people over 70
        var thisOneCounts = test(person);
        //if the person passed the `test` (>70), then 1 is included
        return fromMother + fromFather + (thisOneCounts ? 1 : 0);
    }
    return reduceAncestors(person, combine, 0);
}

//find the percentage of known ancestors, who lived > 70 years
function longLivingPercentage(person) {
    var all = countAncestors(person, function(person) {
        return true;
    });
    var longLiving = countAncestors(person, function(person) {
        //lifespan
        return (person.died - person.born) >= 70;
    });
    //percentage of >70
    return longLiving / all;
}
console.log(longLivingPercentage(byName["Emile Haverbeke"]));
// → 0.145

reduceAncestors 函数:

function reduceAncestors(person, f, defaultValue) {
  function valueFor(person) {
    if (person == null)
      return defaultValue;
    else
      return f(person, valueFor(byName[person.mother]),
                       valueFor(byName[person.father]));
  }
  return valueFor(person);
}

最佳答案

这里发生了很多事情,但要分解一下:

countAncestors 返回 person(包括此人本身)的祖先的数量,这些祖先与提供的测试函数 (test) 中的条件匹配

longLivingPercentage 首先使用 countAncestors 函数来计算指定人的所有 祖先(通过使用始终返回 true 的测试),然后再次使用它来计算指定人的所有 70 岁或以上死亡的祖先。

reduceAncestors 通过递归地寻找每个 parent 然后使用提供的函数 f(在本例中为 combine) 合并结果。

combine,如上所述,用于合并reduceAncestors递归得到的值。它将当前人的父亲和母亲的匹配祖先总数相加,如果匹配测试,则将当前人添加到总数中。

假设一个家谱,其中第一个传入的人 (G) 只有一个父亲和一个母亲(E 和 F),每边有两个祖 parent (A、B、C 和 D),并且测试总是返回 true,对 combine 的递归调用将如下所示:

combine(A,0,0) = 1   combine(B,0,0) = 1   combine(C,0,0) = 1   combine(D,0,0) = 1
       |                    |                    |                   |
       ----------------------                    ---------------------
                |                                          |
        combine(E,1,1) = 3                         combine(F,1,1) = 3
                |                                          |
                --------------------------------------------
                                     |
                             combine(G, 3, 3) = 7

关于javascript - Eloquent JS 第 5 章中的这段代码做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28906527/

相关文章:

javascript - 当鼠标悬停在 LineSegment 的不同部分时,如何实现 raycaster 的准确性?

perl - 在 perl 中重写递归函数,以便它可以在列表上下文中使用

javascript - 处理映射数组中的 React Child

javascript - 用于获取元素 ID 的 AngularJS 指令

C 递归 : return statement

Java像图一样遍历一个大的HashMap

ios - 递归函数,带有完成 block ,检索多个 MKDirections - Swift

java - 在Java中递归构建字符串

javascript - 如何计算任意两个圆SVG的边缘的最小距离

javascript - 元素多时如何克服JQuery MultiSelect 性能问题?