Sve*_*off 2 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
Run Code Online (Sandbox Code Playgroud)
该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);
}
Run Code Online (Sandbox Code Playgroud)
这里有很多事情要做,但要打破它:
countAncestors返回与person提供的测试函数中的条件匹配的祖先(包括他自己)的祖先数(test)
longLivingPercentage首先使用该countAncestors函数计算指定人员的所有祖先(通过使用始终返回的测试true),然后再次使用它来计算在70岁或以上死亡的指定人员的所有祖先.
reduceAncestors通过递归寻找每个父级然后使用提供的函数f(在这种情况下是combine)将结果合并在一起,通过族树扇出.
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
Run Code Online (Sandbox Code Playgroud)