Coffeescript array.sort (a, b) generates JS failure

I am working with coffeescript (version 1.11.1) and I came across something that I am trying to describe. I was just trying to sort an array of objects by field, which I can do this:

data.sort (a,b) -> if a.name < b.name then -1 else if a.name > b.name then 1 else 0 

This creates the following javascript:

 data.sort(function(a, b) { if (a.name < b.name) { return -1; } else if (a.name > b.name) { return 1; } else { return 0; } }); 

Tall. But in my first attempt, I did this instead:

 data.sort(a,b) -> if a.name < b.name then -1 else if a.name > b.name then 1 else 0 

And the generated javascript for this:

 data.sort(a, b)(function() { if (a.name < b.name) { return -1; } else if (a.name > b.name) { return 1; } else { return 0; } }); 

Which is because javascript is so useful, it fails (at least in Chrome) and leads to a premature return of the surrounding function. A little disappointing, but I will overcome it.

First, I want to confirm that this is the expected behavior. I think this is probably the case, and I have some vague thoughts bouncing around my skull about why this is happening, but I was hoping to get a deeper understanding. How should this be described or what terminology is relevant to this feature of the language?

+5
source share
1 answer

This is the expected behavior.


CoffeeScript supports all of the following features:

  • (a, b) -> 5 notation for functions,

  • -> 5 designation for functions without arguments,

  • f(a, b) designation for function calls and

  • fa designation for function calls (implicit parentheses).

So, what do you call the result of calling the function f(a, b) the function parameter -> 5 ?

Answer:

 f(a, b) -> 5 

which, as you noticed, looks pretty similar to -

 f (a, b) -> 5 

which transfers to the call of f , passing the function (a, b) -> 5 as a parameter.

+4
source

Source: https://habr.com/ru/post/1258351/


All Articles