0

I'm trying to translate this Javascript code:

if(error) {
    foo();
    return null;
}
bar()

into Coffeescript code, where here bar() is another long piece of code which I don't want to indent more

Is there a better way than this?

if error
    foo()
    return null
bar()
seldon
  • 977
  • 2
  • 8
  • 20
  • 1
    Maybe you can show more of the function? I suspect it's a node callback, and for that there a many patterns to simplify. – Bergi Sep 29 '14 at 20:23
  • yes, it's the first snippet of a Node callback, but how does it change the question? I'm asking for a general approach. Otherwise, what would you suggest? – seldon Sep 29 '14 at 20:25
  • @mattecapu What better way you are expecting? – Rahil Wazir Sep 29 '14 at 20:29
  • 1
    @mattecapu: I would suggest to use promises. Or, depending on what `foo` is, some generic higher-order wrapper around the callback. – Bergi Sep 29 '14 at 20:58
  • Sure, that's a viable option, but being new to coffeescript I wanted to see how to manipulate such expressions. Apart from this, I'm going to use promises anyway. – seldon Sep 29 '14 at 21:04

3 Answers3

2

Your code looks fine for me.

Though, if you really want it to be a one-liner, you could take advantage of parentheses:

return (foo(); null) if error
Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122
  • 1
    That's what I was looking for. However maybe is too much concise? Do you think it's less readable? – seldon Sep 29 '14 at 20:52
0

What about

if error
    foo()
else
    bar()

(possibly with a trailing return)

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-1

You could rewrite it in an alternate form (slightly different symatically, since you're returning the result of foo()):

return foo() if error
C.K
  • 1
  • 1