Skip to content

Instantly share code, notes, and snippets.

@davidpdrsn
Created June 1, 2014 17:37
Show Gist options
  • Save davidpdrsn/ddb163b07b842978d763 to your computer and use it in GitHub Desktop.
Save davidpdrsn/ddb163b07b842978d763 to your computer and use it in GitHub Desktop.
Useful higher order functions in CoffeeScript
add = (x, y) -> x+y
squared = (x) -> x*x
console.log f.curry(add)(1)(2)
console.log f.curry(Array::map, [1,2,3])(squared)
f.flip(f.join)((-> console.log "hi"), (-> console.log "there"))()
f =
flip: (fn, context = this) ->
toArray = (x) -> Array::slice.call(x, 0)
->
reversed_args = toArray(arguments).reverse()
fn.apply(context, reversed_args)
curry: (->
append = (x, a) ->
a.push x
a
buildCurried = (fn, arity, args, context) ->
if arity == 1
(x) -> fn.apply context, append(x, args)
else
(x) -> buildCurried fn, arity-1, append(x, args), context
(fn, context, arity) ->
arity ||= fn.length
context ||= fn
buildCurried fn, arity, [], context
)()
join: () ->
fns = Array.prototype.slice.call(arguments, 0)
->
args = arguments
fns.forEach (fn) -> fn.apply(fn, args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment