我一直在阅读《Ruby 重构》一书(Fields、Harvie、Fowler)。他们提到提取周围方法操作,如果您有中间部分彼此不同的方法,可以使用它来避免重复。
def number_of_descendants_named(name)
count_descendants_matchin { |descendant| descendant.name == name }
end
def number_of_living_descendants
count_descendants_matching { |descendant| descendant.alive? }
end
def count_descendants_mathing(&block)
children.inject(0) do |count, child|
count += 1 if yield child
count + child.count_descendants_matching(&block)
end
end
我相信您已经明白了。你会如何用 Javascript 做类似的事情?
最佳答案
Javascript也有闭包,所以很简单,只需将 block 转换为匿名函数,代码实际上是相同的:
var number_of_descendants_named = function(name) {
return count_descendants_matching(function(descendant) {
return descendant.name == name;
});
};
var number_of_living_descendants = function(descendant) {
return count_descendants_matching(function(descendant) {
return descendant.alive();
});
};
var count_descendants_mathing = function(cb) {
// reduce: use underscore or any other functional library
return somelib.reduce(children, 0, function(count, child) {
return count + (cb(child) ? 1 : 0) + child.count_descendants_matching(cb)
});
};
这种函数式风格(一切都是要返回的表达式)在普通 Javascript 中非常冗长,但某些 altJS 语言(例如 Coffeescript)将其简化了很多。
关于提取周围方法的 JavaScript 版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11878070/