2012-08-09 51 views
2

我一直在阅读Ruby重构书(Fields,Harvie,Fowler)。他们提到Extract Surrounding Method操作,如果您有中间部分彼此不同的方法,可以使用它来避免重复。Javascript版本的提取周边方法

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?

回答

3

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

+0

感谢您的快速回答!这正是我所期待的! – hade 2012-08-09 06:55:33