-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsnippets-functional-p.ts
98 lines (88 loc) · 2.1 KB
/
snippets-functional-p.ts
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Functional programming
// from https://medium.com/better-programming/functional-programming-in-javascript-introduction-and-practical-examples-d268e44395b2
/**
* Instead of for loops.
*/
const list1to100 = () => {
return new Array(100).fill(null).map((x, i) => i + 1);
};
// or in short...
Array(10)
.fill(null)
.map((x, i) => console.log(i));
/**
* Basic compose function.
*/
const compose = (...fns) => x => fns.reduceRight((res, fn) => fn(res), x);
// Usage
const centsToDollars = compose(
addSeparators,
addDollarSign,
roundTo2dp,
divideBy100
);
/**
* Basic Pipe function in typescript
*/
const pipe = <T>(...fns: Array<(arg: T) => T>) => (value: T) => fns.reduce((acc, fn) => fn(acc), value);
/**
* Use tap and Trace for debugging inside compose
*/
const tap = f => x => {
f(x);
return x;
};
const trace = label => tap(console.log.bind(console, label + ':'));
// Debugging implemented to use case.
const centsToDollars = compose(
trace('addSeparators'),
addSeparators,
trace('addDollarSign'),
addDollarSign,
trace('roundTo2dp'),
roundTo2dp,
trace('divideBy100'),
divideBy100,
trace('argument')
);
/* Output
argument: 100000000
divideBy100: 1000000
roundTo2dp: 1000000.00
addDollarSign: $1000000.00
addSeparators: $1,000,000.00
*/
/**
* Container
* Use a container to encapsulate "side-effecty" operations.
*/
class Container {
constructor(fn) {
this.value = fn;
if (!isFunction(this.value) && !isAsync(this.value)) {
throw new TypeError(
`Container expects a function, not a ${typeof this.value}.`
);
}
}
run() {
return this.value();
}
map(fn) {
if (!isFunction(fn) && !isAsync(fn)) {
throw new TypeError(
`The map method expects a function, not a ${typeof fn}.`
);
}
return new Container(() =>
isPromise(this.value()) ? this.value().then(fn) : fn(this.value())
);
}
}
// Usage
const sayHello = () => 'Hello';
const addName = (name, str) => str + ' ' + name;
const container = new Container(sayHello);
const greet = container
.map(addName.bind(this, 'Joe Bloggs'))
.map(tap(console.log));