-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01.introduction-box.js
More file actions
61 lines (45 loc) · 1.2 KB
/
01.introduction-box.js
File metadata and controls
61 lines (45 loc) · 1.2 KB
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
/**
* Create linear data flow with container style types
*
*/
const { Box } = require('./box.js');
// Imperative style
function imperative () {
const nextCharForNumberString = str => {
const trimmed = str.trim();
const number = parseInt(trimmed);
const nextNumber = number + 1;
return String.fromCharCode(nextNumber);
};
const result = nextCharForNumberString(' 64 ');
return result;
}
console.log('Imperative: ', imperative());
// Intermediate
function intermediate () {
const nextCharForNumberString = str => {
return String.fromCharCode(parseInt(str.trim()) + 1); // unreadable/confusing
};
const result = nextCharForNumberString(' 64 ');
return result;
}
console.log('Intermediate: ', intermediate());
// Functional style
function functional () {
const Box = x => ({
map: f => Box(f(x)),
fold: f => f(x),
inspect: () => `Box('${x}')`
});
const trim = s => s.trim();
const addOne = n => n + 1;
const nextCharForNumberString = str =>
Box(str)
.map(trim)
.map(parseInt)
.map(addOne)
.fold(String.fromCharCode);
const result = nextCharForNumberString(' 64 ');
return result;
}
console.log('Functional: ', functional());