what does ":" mean in this case in coffee script? - coffeescript

I am new to coffee script. When I am looking at this document https://atom.io/docs/api/v0.198.0/CommandRegistry#instance-add
I see a code segment like,
atom.commands.add 'atom-text-editor',
'user:insert-date': (event) ->
editor = #getModel()
editor.insertText(new Date().toLocaleString())
while the function signature looks,
::add(target, commandName, callback)
So in the code segment, what does : on the second line mean? My understanding is the 'user:insert-date' before : is commandName in the signature. The thing after : is "callback". So : is a argument separator like a ,? I don't find this introduced in the coffee script document http://coffeescript.org

That colon is just part of an object literal. The braces around object literals are optional in CoffeeScript when there's no ambiguity. If we add the optional braces, we get something that looks more like JavaScript:
atom.commands.add 'atom-text-editor', {
'user:insert-date': (event) ->
#...
}
So atom.commands.add is being called with two arguments. The first is the string 'atom-text-editor' and the second is an object with one key ('user:insert-date') whose value is an anonymous function that takes a single argument.

Appending mu is too short's answer (the user is absolutely correct that the second parameter commandNamecan be an object without the explicit braces {})
Atom's sourcecode:
https://github.com/atom/atom/blob/v0.198.0/src/command-registry.coffee#L81
add: (target, commandName, callback) ->
if typeof commandName is 'object'
commands = commandName
disposable = new CompositeDisposable
for commandName, callback of commands
disposable.add #add(target, commandName, callback)
return disposable

Related

Add method to string class in node.js express.js coffeescript

I want to add some my methods to generic types like string, int etc. in express.js (coffeescript). I am completely new in node. I want to do just this:
"Hi all !".permalink().myMethod(some).myMethod2();
5.doSomething();
variable.doSomethingElse();
How to do this ?
You can add a method to the String prototype with:
String::permaLink = ->
"http://somebaseurl/archive/#{#}"
String::permalink is shorthand for String.prototype.permaLink
You can then do:
somePermalink = "some-post".permaLink()
console.log somePermalink.toUpperCase()
This will call the the "String.prototype.permaLink" function with "this" set to the "some-post" string. The permaLink function then creates a new string, with the string value of "this" (# in Coffeescript) included at the end. Coffeescript automatically returns the value of the last expression in a function, so the return value of permaLink is the newly created string.
You can then execute any other methods on the string, including others you have defined yourself using the technique above. In this example I call toUpperCase, a built-in String method.
You can use prototype to extend String or int object with new functions
String.prototype.myfunc= function () {
return this.replace(/^\s+|\s+$/g, "");
};
var mystring = " hello, world ";
mystring.myfunc();
'hello, world'

How to define a default argument value for a method in as2?

look at this code :
function a2j(trusted:Boolean=true):String
{
...
}
compiler will not accept this code in flash actionscript 2.
It looks like AS2 doesn't force you to supply the all the arguments that a function declares. At the bottom of this help page, they state that arguments you do not supply are undefined ... and that any extra arguments you supply are ignored.
Also, the answer to this question shows that you can use the arguments keyword (an Array) to work with the parameters that are passed into the function.
So for a default value, as in your example above, you could do something like this:
function methodThatHasADefault(value:Boolean):void
{
if (arguments.length == 0)
value = true;
// do something
}

Correct way to return function value instead of binding in Coffeescript

I can't seem to find a concise answer to this question. What is the correct coffeescriptic way to return the value from _otherInstanceMethod when calling #_instanceMethod instead of the function binding itself?
x = _instanceMethod: () ->
#_otherInstanceMethod key: 'value'
Edit (thanks commenters)
This returns:
x = function () {
[...] # function body omitted
});
Instead of
x = 'some value returned by _otherInstanceMethod'
I would like the value to be returned instead of the function binding to _otherInstanceMethod
Being totally new to Coffeescript, this was my fault. I was calling the instance method like:
#_instanceMethod
instead of
#_instanceMethod()
Sorry for the trouble, voting to delete
In CoffeeScript #something translated into this.something regardless of the underlying variable type. This means you can use # only in conjuction with properties, with methods you still ought to use good old this.

Why is param in this lambda expression?

The MSDN magazine article by Josh Smith on MVVM contains a lambda expression I don't completely understand. What is the purpose of param in this code?
_saveCommand = new RelayCommand(param => this.Save(),
param => this.CanSave );
Translated to my preferred language VB it's:
Dim saveAction as New Action(Of Object)(AddressOf Me.Save)
_saveCommand = New RelayCommand(saveAction, Function(param) Me.CanSave)
I would have expected to only see param if it is used within CanSave or Save. I am somewhat new to lambda expressions. It's odd for me to see a variable that is neither declared nor used anywhere as far as I can tell. Any explanation would be appreciated.
To put this in context the constructor for RelayCommand (C#) is:
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
and in VB:
Public Sub New(ByVal execute As Action(Of Object), _
ByVal canExecute As Predicate(Of Object))
The lambda expression is declaring it - the place where it appears is basically a declaration. If it didn't, it wouldn't be compatible with Action(Of Object). That's why it's there - even though you don't actually need the value.
With anonymous methods, if you don't need any parameter values you can omit the parameter list entirely:
_saveCommand = new RelayCommand(delegate { this.Save(); },
delegate { return this.CanSave; });
... but you can't do that with lambda expressions. You have to specify the parameter list - either just as a parameter name for a single parameter, or a full list in brackets. The code you've presented is equivalent to:
_saveCommand = new RelayCommand((Object param) => this.Save(),
(Object param) => this.CanSave);

What does () => mean in C#?

I've been reading through the source code for Moq and I came across the following unit test:
Assert.Throws<ArgumentOutOfRangeException>(() => Times.AtLeast(0));
And for the life of me, I can't remember what () => actually does. I'm think it has something to do with anonymous methods or lambdas. And I'm sure I know what it does, I just can't remember at the moment....
And to make matters worse....google isn't being much help and neither is stackoverflow
Can someone give me a quick answer to a pretty noobish question?
Search StackOverflow for "lambda".
Specifically:
() => Console.WriteLine("Hi!");
That means "a method that takes no arguments and returns void, and when you call it, it writes the message to the console."
You can store it in an Action variable:
Action a = () => Console.WriteLine("Hi!");
And then you can call it:
a();
()=> is a nullary lambda expression. it represents an anonymous function that's passed to assert.Throws, and is called somewhere inside of that function.
void DoThisTwice(Action a) {
a();
a();
}
Action printHello = () => Console.Write("Hello ");
DoThisTwice(printHello);
// prints "Hello Hello "
It's a lambda expression. The most common syntax is using a parameter, so there are no parentheses needed around it:
n => Times.AtLeast(n)
If the number of parameters is something other than one, parentheses are needed:
(n, m) => Times.AtLeast(n + m)
When there are zero parameters, you get the somewhat awkward syntax with the parentheses around the empty parameter list:
() => Times.AtLeast(0)
() => Times.AtLeast(0)
() indicates that the lambda function has no parameters or return value.
=> indicates that a block of code is to follow.
Times.AtLeast(0) calls the Times class's static method AtLeast with a parameter of 0.
That's the definition of a lambda (anonymous) function. Essentially, it's a way to define a function inline, since Assert.Throws takes a function as an argument and attempts to run it (and then verify that it throws a certain exception).
Essentially, the snippet you have there is a unit test that makes sure Times.AtLeast(0) throws a ArgumentOutOfRangeException. The lambda function is necessary (instead of just trying to call the Times.AtLeast function directly from Assert.Throws) in order to pass the proper argument for the test - in this case 0.
MSDN KB article on the topic here: http://msdn.microsoft.com/en-us/library/bb882516.aspx
I don't program in C#, but Googling "C# Lambda" provided this link that answers your question!!!