2

我一直在阅读 Ruby Refactoring 书(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 做类似的事情?

4

1 回答 1

4

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

于 2012-08-09T06:51:40.420 回答