Instantly share code, notes, and snippets.

# zfogg/curry.coffeeSecret Last active Oct 1, 2015

Tools to partially apply functions with their arguments.
 # USAGE: Math.pow.curry()(2)(5) # == 32 Math.pow.curry()(2, 5) # == 32 Math.pow.curry(2, 5) # == 32 Math.pow.curry(2)(5) # == 32 # It works with any number of args: ((a,b,c,d) -> [a,b,c,d]).curry(1)(2,3)(4) # == [1,2,3,4] # curryFlip is like curry, but the args are applied in reverse. Math.pow.curryFlip(5)(2) # == 32 ((a,b,c,d) -> [a,b,c,d]).curry(1)(2,3)(4) # == [4,3,2,1] # And just for laughs: Math.pow.curry()()()(2)()()()(5) # == 32 # Function::curry Fn = partial: (f, args1...) -> (args2...) -> f.apply @, args1.concat args2 partial\$: (f, args) -> Fn.partial.apply @, [f].concat args flip: (f, args1...) -> (args2...) -> f.apply @, (args1.concat args2).reverse() flip\$: (f, args) -> Fn.flip.apply @, [f].concat args curry: (n, f, args...) -> Fn.curry\$ (n - args.length), (Fn.partial\$ f, args) curryFlip: (n, f, args...) -> Fn.curry\$ (n - args.length), (Fn.flip\$ f, args) curry\$: (n, f, args...) -> if n > args.length Fn.partial Fn.curry\$, (n - args.length), (Fn.partial\$ f, args) else f.apply @, args Function::curry = (args...) -> Fn.curry.apply @, [@length, @].concat args Function::curryFlip = (args...) -> Fn.curryFlip.apply @, [@length, @].concat args