-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathfunction_composition.js
49 lines (37 loc) · 1.36 KB
/
function_composition.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
const log = (...args) => console.log(...args);
/*
Function Composition combines two or more functions together
To perform function composition,
you simply have the result of each function be passed as the argument to the next
As an example we'll implement a simple function that calculates total purchase price
by taking the purchase price, applying an 8% tax, and adding $10 (shipping and handling)
*/
const calculateTotalBasic = (amount) => {
return (amount * 1.08) + 10;
}
/*
Now let's refactor it:
- implement applyTax function
- implement applyShippingAndHandling
- compose those functions into the calculate function
*/
const applyTax = (amount) => amount * 1.08;
const applyShippingAndHandling = (amount) => amount + 10;
const calculateTotal = (amount) => {
return applyShippingAndHandling(applyTax(amount));
}
// compose function using reduce
const compose = (...fns) => (x) => {
return fns.reduceRight((composedFns, fn) => fn(composedFns), x)
};
const shoutBasic = (str) => `${str.toUpperCase()}!`;
log(shoutBasic('something'));
log(shoutBasic('something else'));
log(shoutBasic('nothing'));
// compose toUpperCase and exclaim functions
const toUpperCase = (str) => str.toUpperCase();
const exclaim = (str) => `${str}!`;
const shout = compose(exclaim, toUpperCase);
log(shout('something'));
log(shout('something else'));
log(shout('nothing'));