|
| 1 | +// Chapter 02: First Class Functions |
| 2 | + |
| 3 | +const hi = name => `Hi ${name}`; |
| 4 | + |
| 5 | +// const greeting = name => hi(name); |
| 6 | +// this is totally redundant, |
| 7 | +// because we can treat the greeting function as a value |
| 8 | +// and assign this value to the new greeting function, like that: |
| 9 | + |
| 10 | +const greeting = hi; |
| 11 | + |
| 12 | +// and use it normal function |
| 13 | +greeting('TK'); // Hi TK |
| 14 | + |
| 15 | +// Another more complex example |
| 16 | +// This function `const getServerStuff = callback => ajaxCall(json => callback(json));` is the same as this: |
| 17 | +const getServerStuff = ajaxCall; |
| 18 | + |
| 19 | +// Simplifying this function: |
| 20 | +// 1. const getServerStuff = callback => ajaxCall(json => callback(json)); |
| 21 | +// 2. const getServerStuff = callback => ajaxCall(callback); |
| 22 | +// 3 const getServerStuff = ajaxCall; |
| 23 | + |
| 24 | +// Treating functions as values (first class), it easier to maintain. |
| 25 | +// If we have a wrapped function and it needs to change, we need to change both the wrapped function and the call |
| 26 | + |
| 27 | +// We have this httpGet function |
| 28 | +httpGet('/post/2', json => renderPost(json)); |
| 29 | + |
| 30 | +// But we need to change the renderPost function to receive not only the json, but also the error (err) |
| 31 | +// We change the renderPost function and the calling |
| 32 | +httpGet('/post/2', json, err => renderPost(json, err)); |
| 33 | + |
| 34 | +// Another approach is to treat functions as values and return the renderPost function |
| 35 | +// This way we only need to change the renderPost function. The httpGet function stays the same |
| 36 | +httpGet('/post/2', renderPost); |
0 commit comments