Skip to content

Instantly share code, notes, and snippets.

@shesek
Created February 29, 2012 03:32
Show Gist options
  • Save shesek/1937375 to your computer and use it in GitHub Desktop.
Save shesek/1937375 to your computer and use it in GitHub Desktop.
CoffeeScript object creating helper
# 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()
@shesek
Copy link
Author

shesek commented Feb 29, 2012

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