Skip to content

Commit 0184315

Browse files
committed
Add "Functions/Splat Arguments" recipe.
1 parent d115f0c commit 0184315

File tree

3 files changed

+52
-2
lines changed

3 files changed

+52
-2
lines changed

chapters/functions/recursion.textile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,5 @@ setTimeout((->
3131

3232
h2. Discussion
3333

34+
While @arguments.callee@ allows for the recursion of anonymous functions and might have the advantage in a very memory-intensive application, named functions keep their purpose more explicit and make for more maintainable code.
35+
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
---
2+
layout: recipe
3+
title: Splat Arguments
4+
chapter: Functions
5+
---
6+
7+
h2. Problem
8+
9+
Your function will be called with a varying number of arguments.
10+
11+
h2. Solution
12+
13+
Use _splats_.
14+
15+
{% highlight coffeescript %}
16+
loadTruck = (firstDibs, secondDibs, tooSlow...) ->
17+
truck:
18+
driversSeat: firstDibs
19+
passengerSeat: secondDibs
20+
trunkBed: tooSlow
21+
22+
loadTruck("Amanda", "Joel")
23+
# => { truck: { driversSeat: "Amanda", passengerSeat: "Joel", trunkBed: [] } }
24+
25+
loadTruck("Amanda", "Joel", "Bob", "Mary", "Phillip")
26+
# => { truck: { driversSeat: "Amanda", passengerSeat: "Joel", trunkBed: ["Bob", "Mary", "Phillip"] } }
27+
{% endhighlight %}
28+
29+
With a trailing argument:
30+
31+
{% highlight coffeescript %}
32+
loadTruck = (firstDibs, secondDibs, tooSlow..., leftAtHome) ->
33+
truck:
34+
driversSeat: firstDibs
35+
passengerSeat: secondDibs
36+
trunkBed: tooSlow
37+
taxi:
38+
passengerSeat: leftAtHome
39+
40+
loadTruck("Amanda", "Joel", "Bob", "Mary", "Phillip", "Austin")
41+
# => { truck: { driversSeat: "Amanda", passengerSeat: "Joel", trunkBed: ["Bob", "Mary", "Phillip"] }, taxi: "Austin" }
42+
{% endhighlight %}
43+
44+
loadTruck("Amanda")
45+
# => { truck: { driversSeat: "Amanda", passengerSeat: undefined, trunkBed: [] }, taxi: undefined }
46+
47+
h2. Discussion
48+
49+
By adding an ellipsis ("...") next to no more than one of a function's arguments, CoffeeScript will combine all of the argument values not captured by other named arguments into a list. It will serve up an empty list even if some of the named arguments were not supplied.
50+

wanted-recipes.textile

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,6 @@ foo 1, 2, 3
9393
# => 6
9494
{% endhighlight %}
9595

96-
* Variable arguments with splats
97-
9896
h2. jQuery
9997

10098
h2. Regular Expressions

0 commit comments

Comments
 (0)