2

Ruby Refactoring の本 (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 でどのように同様のことを行いますか?

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 に答える