gpt4 book ai didi

提取周围方法的Javascript版本

转载 作者:数据小太阳 更新时间:2023-10-29 08:51:28 24 4
gpt4 key购买 nike

我一直在阅读《Ruby 重构》一书(Fields、Harvie、Fowler)。他们提到了 Extract Surrounding Method 操作,如果你有中间部分彼此不同的方法,可以用来避免重复。

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com