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
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(); }).
CoffeeScript tends to run as fast, or faster than hand-written JavaScript.
As of today, January 2020, CoffeeScript is completely dead on the market (though the GitHub repository is still kind of alive).
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With