Eloquent JS第5章的代码是做什么的?

时间:2015-03-06 19:51:16

标签: 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);
}

1 个答案:

答案 0 :(得分:6)

这里有很多事情要做,但是要分解它:

countAncestors返回与提供的测试函数(person)中的条件匹配的test(包括他自己)的祖先数

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

reduceAncestors通过递归搜索每个父级,然后使用提供的函数f(在本例中为combine)将结果合并在一起,从而通过族树扇出。< / p> 如上所述,

combine用于合并reduceAncestors递归获得的值。它为当前人的父亲和母亲添加了匹配祖先的总数,然后如果他们匹配测试,则将当前人员添加到该总数中。

假设一个家庭树,其中传入的初始人(G)只有一个父亲和母亲(E和F),以及两侧的两个祖父母(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