2012-08-09 55 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