Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript run function or read variable

Tags:

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 
like image 296
nicklovescode Avatar asked Nov 27 '11 03:11

nicklovescode


People also ask

How do you call a function in CoffeeScript?

You can simply invoke a function by placing parenthesis after its name as shown in the following example. // Generated by CoffeeScript 1.10. 0 (function() { var add; add = function() { var a, b, c; a = 20; b = 30; c = a + b; return console. log("Sum of the two numbers is: " + c); }; add(); }).

Is CoffeeScript slower than JavaScript?

CoffeeScript tends to run as fast, or faster than hand-written JavaScript.

Is CoffeeScript still a thing?

As of today, January 2020, CoffeeScript is completely dead on the market (though the GitHub repository is still kind of alive).


1 Answers

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..

like image 153
Trevor Burnham Avatar answered Oct 18 '22 08:10

Trevor Burnham