提取周围方法的 JavaScript 版本

Javascript version of extract surrounding method

本文关键字:JavaScript 版本 方法 周围 提取      更新时间:2023-09-26

我一直在读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 也有闭包,所以这很容易,只需将块转换为匿名函数,代码实际上是相同的:

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)简化了它。