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() |
Actually, coming to think about that - assuming you don't need the preserve the external this
context and don't mind always adding am empty return
(which you should do anyway), simply using new
can work just as well:
doStuff = -> new -> @[k] = 123 for k in ['a','b','c'];return
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do note that the for loop inside the anonymous function generates a return value (as do all expressions in CoffeeScript), so you might want to use an empty
return
statement after the object creation to avoid creating an array with the results for each iteration (compare this to that).