@@ -7,6 +7,7 @@ A Cookbook for writing FP in JavaScript using ES6
7
7
* [ Higher-order functions] ( #higher-order-functions )
8
8
* [ Recursion] ( #recursion )
9
9
* [ Functor] ( #functor )
10
+ * [ Compose] ( #compose )
10
11
* [ Destructuring] ( #destructuring )
11
12
* [ Currying] ( #currying )
12
13
@@ -165,6 +166,38 @@ numbers.map(plus1);
165
166
// [2, 3, 4]
166
167
```
167
168
169
+ ### Compose
170
+ The composition of two or more functions returns a new function.
171
+
172
+ 1 ) Combining two functions to generate another one
173
+
174
+ ``` javascript
175
+ let compose = (f ,g ) => x => f (g (x));
176
+
177
+ let toUpperCase = function (x ) { return x .toUpperCase (); };
178
+ let exclaim = function (x ) { return x + ' !' ; };
179
+
180
+ let angry = compose (exclaim, toUpperCase);
181
+
182
+ angry (" stop this" );
183
+ // STOP THIS!
184
+ ```
185
+
186
+ 2 ) Combining three functions to generate another one
187
+
188
+ ``` javascript
189
+ let compose = (f ,g ) => x => f (g (x));
190
+
191
+ let toUpperCase = function (x ) { return x .toUpperCase (); };
192
+ let exclaim = function (x ) { return x + ' !' ; };
193
+ let moreExclaim = function (x ) { return x + ' !!!!!' ; };
194
+
195
+ let reallyAngry = compose (exclaim, (toUpperCase, moreExclaim));
196
+
197
+ reallyAngry (" stop this" );
198
+ // STOP THIS!!!!!!
199
+ ```
200
+
168
201
### Destructuring
169
202
Extract data from arrays or objects using a syntax that mirrors the construction of array and object literals. Or "Pattern Matching".
170
203
@@ -208,10 +241,7 @@ Taking a function that takes multiple arguments and turning it into a chain of f
208
241
1 ) Currying an Object
209
242
210
243
``` javascript
211
- let student =
212
- name =>
213
- grade =>
214
- ` Name: ${ name} | Grade: ${ grade} ` ;
244
+ let student = name => grade => ` Name: ${ name} | Grade: ${ grade} ` ;
215
245
216
246
student (" Matt" )(8 );
217
247
// Name: Matt | Grade: 8
@@ -220,10 +250,7 @@ student("Matt")(8);
220
250
2 ) Currying a Sum
221
251
222
252
``` javascript
223
- let currySum =
224
- x =>
225
- y =>
226
- x + y;
253
+ let currySum = x => y => x + y;
227
254
228
255
let addFive = currySum (5 );
229
256
addFive (10 );
0 commit comments