nicklovescode
nicklovescode

Reputation: 213

Coffeescript run function or read variable

Say I have either

msg = "Saved Successfully"

or

msg = -> "Saved #{@course.title} Successfully"

Is there anyway to elegantly get the value of msg without knowing whether it's a function or a regular variable rather than doing

success_message = if typeof msg is 'function' then msg() else msg

Upvotes: 21

Views: 3935

Answers (1)

Trevor Burnham
Trevor Burnham

Reputation: 77416

There's a CoffeeScript shorthand you can take advantage of:

f?()

is equivalent to

f() if typeof f is 'function'

which means that you can write

success_message = msg?() ? msg

This works because msg?() has the value undefined if msg isn't a function.

Caveat: This will fail if msg() returns null, setting success_message to the msg function.

Really, if you're going to do this in your application, you should write a utility function:

toVal = (x) -> if typeof x is 'function' then x() else x
successMessage = toVal msg

You could even attach toVal to the Object prototype if you're feeling adventurous..

Upvotes: 38

Related Questions