Created
June 1, 2014 17:37
-
-
Save davidpdrsn/ddb163b07b842978d763 to your computer and use it in GitHub Desktop.
Useful higher order functions in CoffeeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"))() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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