-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhigher-order-functions.js
84 lines (74 loc) · 2.24 KB
/
higher-order-functions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* A higher order function is a function that takes a function
* as an argument, or returns a function.
*
* The main purpose of higher order functions is to abstract away
* the commonalities within functions. Higher-order functions allow
* us to abstract actions, not just values.
*
* Some typical use cases include:
* 1. function factories
* 2. consolidate logical checks
* 3. manipulate control flow
*
* Some benefits include:
* 1. cleaner code
* 2. more reusable code
* 3. has the potential to be much easier to read
*
* https://eloquentjavascript.net/05_higher_order.html
*
* Built in examples:
* .map()
* .filter()
* .reduce()
*/
/************************************************
*
* Function factories
*
************************************************/
function greaterThan(n) {
return m => m > n
}
/**
* A great benefit as you can see here is that code is much more readable.
*
* Darren (Sim) talks about how great code is when non-devs can look at the
* code and understand flow. Having the function called greaterThan10 is
* much easier to read in the context of the call-site than the function
* greaterThan(10) because you would have to dive into the parameters.
*
* The other thing is... now that you have the function greaterThan10, you can
* reuse that instead of calling greaterThan(10) every single time. It also
* gives you a single point for change should you need it.
*/
const greaterThan10 = greaterThan(10)
const greaterThan100 = greaterThan(100)
// Example 2
function multiplyBy(n) {
return m => m * n
}
const tripple = multiplyBy(3)
const quadruple = multiplyBy(4)
/************************************************
*
* Moving logical checks into small
* reusable components
*
************************************************/
const isDog = function(animal) {
return animal.species === 'dog'
}
const dogs = animals.filter(isDog)
const otherAnimals = animals.reject(isDog)
/************************************************
*
* Control Flow Manipulation
*
************************************************/
function doWhen(conditional, fn) {
if (conditional) fn()
}
doWhen(greaterThan10(11), () => console.log('hey'))
doWhen(greaterThan10(9), () => console.log("I won't be run"))