I’ve been reading Ruby Refactoring book (Fields, Harvie, Fowler). They mention Extract Surrounding Method operation which can be used to avoid duplication if you have methods which middle part is different from each other.
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
I’m sure you get the idea. How would you do similar with Javascript?
Javascript has also closures, so it’s pretty easy, just convert blocks into anonymous functions and the code is practically the same:
This functional style where everything is a expression to be returned is very verbose in plain Javascript, but some altJS languages (for example Coffeescript) simplify it a lot.