0

What's the correct way to pass a function as a parameter in liveScript?

For instance, lets say I Want to use the array reduce function, in convectional javascript I would write it as the following

myArray.reduce(function (a,b) {return a + b});

This translates to liveScript quite nicely as:

myArray.reduce (a,b) -> a + b

Now, I want to set the initial value by providing a second parameter:

myArray.reduce(function (a,b) {return a + b},5);

How would I translate this to liveScript? It seems that the first function overrides any ability to pass additional parameters to reduce.

Apologies if I have missed something obvious, but I can't seem to find anything pertaining to this scenario in the docs

Sam
  • 1,315
  • 2
  • 13
  • 27

4 Answers4

2

For more complex functions I'd recommend you to use this style

[1, 2, 3].reduce do
  (a, b) ->
    # your code here
  0
Daniel K
  • 91
  • 1
  • 6
2

You can use ~ to bind the this argument, then call flip on it to swap the first and second parameters:

flip [1, 2, 3]~reduce, 0, (a, b) -> a + b

This may be more readable if the callback body is very long.

1

You have to wrap the closure in ()

[1,2,3].reduce ((a,b) -> a + b), 0

Compiles to

[1, 2, 3].reduce(function(a, b){
  return a + b;
}, 0);
Mulan
  • 129,518
  • 31
  • 228
  • 259
0

Just to complement the other answer, LiveScript offers binops, just put parentheses around the operator.

[1 2 3].reduce (+), 0
Ven
  • 19,015
  • 2
  • 41
  • 61