Higher-Order Functions in CoffeeScript

A spiffy trick for working with higher-order functions in CoffeeScript.

by brendanjerwin

CoffeeScript

console.log = (msg)-> $('body').append "<p>#{msg}</p>"

#http://en.wikipedia.org/wiki/Higher-order_function
#higher-order function (takes a function to morph behavior)
count = (items, matching)-> 
  (item for item in items when matching item).length

#stick some useful colaborating functions right on the higher-order function
count.eql = (target)-> 
  (item)-> item == target
  
count.lessThan = (target)->
  (item)-> item < target
  
count.greaterThan = (target)->
  (item)-> item > target


  
#usage
samples = [1,2,3,4,5,1,2,3,5,3,1,2,5,6]
console.log 'Equal: ' + count samples, count.eql 5
console.log 'Greater: ' + count samples, count.greaterThan 4