Created
February 29, 2012 03:32
-
-
Save shesek/1937375 to your computer and use it in GitHub Desktop.
CoffeeScript object creating helper
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
# A tiny helper for creating objects with dynamic keys. I found myself repeating the following pattern all over my code: | |
doStuff = -> | |
obj = {} | |
obj[k] = foo for k in bar() | |
obj | |
# Which is not very elegant, and in many cases forces me to expand one-line functions into multiple lines. | |
# Instead, its possible to move the repeated pattern into a separate function: | |
create = (fn) -> obj = {}; fn.call obj, obj; obj | |
# Than, we can do | |
doStuff = -> create -> @[k]=foo for k in bar() | |
# Or, if you need to preserve the `this` context and can't use `@`: | |
doStuff = -> create (o) => o[k] = foo for k in @bar() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Actually, coming to think about that - assuming you don't need the preserve the external
this
context and don't mind always adding am emptyreturn
(which you should do anyway), simply usingnew
can work just as well: