Created
July 18, 2011 05:36
-
-
Save oblique63/1088619 to your computer and use it in GitHub Desktop.
Clojure's "doto" 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
doto = (object, operations...) -> | |
process = (operation) -> | |
for method, arguments of operation | |
# Additional fancy nonsense to keep things DRY | |
if method is 'repeatedly' | |
[method, arguments] = [name,args] for name, args of arguments | |
operation = {} | |
for argument in arguments | |
operation["#{method}"] = argument | |
process operation | |
continue | |
else | |
arguments = [arguments] if typeof arguments isnt 'object' | |
try | |
object[method](arguments...) | |
catch error | |
throw "Invalid operation on #{object}: #{method}(#{arguments})" | |
for operation in operations | |
process operation | |
# Example Usage: | |
class People | |
@talk: (name, message) -> alert "#{name} says #{message}" | |
@greet: (name) -> alert "#{name} said hello!" | |
@read: -> alert "You must have me confused with the magazine..." | |
doto People, | |
greet: "Dan" | |
repeatedly: talk: [ | |
["Sam", "hello world"] | |
["Max", "que?"] | |
] | |
, | |
read: "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment