Reputation: 67360
Here's a contrived example I've come up with:
fn = (f, a, b, c)-> alert("#{f() + a + b + c}")
fn((-> "hi"), 1, 2, 3)
I'm wondering what's the suggested way to format that last line? This example is easy to understand, but imagine if the anonymous function (the (-> "hi")
) was multi-line and took multiple arguments. This code would become very ugly and start to look lisp-like.
fn2 = (f, a, b, c)-> alert("#{f(1, 2) + a + b + c}")
fn2(((a, b) ->
c = a + b
c), 1, 2, 3)
This can get pretty nasty. Is there some way I should format this code to make it more readable or is the best advice to name the anonymous function?
I notice a few similar questions asking how to do this. The difference here is I'm asking how to format it.
Upvotes: 1
Views: 68
Reputation: 231395
In the Coffeescript documentation there's an example with function parameter last
task 'build:parser', 'rebuild the Jison parser', (options) ->
require 'jison'
code = require('./lib/grammar').parser.generate()
dir = options.output or 'lib'
fs.writeFile "#{dir}/parser.js", code
The Coffeescript test files have lots of examples with function last
test "multiple semicolon-separated statements in parentheticals", ->
nonce = {}
eq nonce, (1; 2; nonce)
eq nonce, (-> return (1; 2; nonce))()
It's when the function isn't last that you need messier indentation and commas, or extra parenthesis to define the function's boundaries.
Upvotes: 1
Reputation: 19219
I've seen this style used a couple of times:
fn2 (a, b) ->
a + b
, 1, 2, 3
For example, in setTimeout
calls:
setTimeout ->
alert '1 second has passed'
, 1000
But i think in general it's better to separate the parameter function in a variable:
add = (a, b) ->
a + b
fn2 add, 1, 2, 3
Or, if it's possible to change the function definition, make the function parameter the last one:
fn2 1, 2, 3, (a, b) ->
a + b
Upvotes: 2