UNPKG

2.07 kBMarkdownView Raw
1# Keyu
2
3**Key u**tilities you will need for any complex javascript project.
4
5## Utilities
6
7### Functional programming
8
9#### Compose
10
11Composes N functions into another one, also accept functions that a return Promise.
12
13```
14const {compose} = require('keyu');
15
16const sum1 = x => x+1;
17const mult2 = x => x*2;
18const dbSum = x => Promise.resolve(x+1);
19
20const sumAndMult = compose(mult2,sum1);
21const sumAndMultDB = compose(dbSum,mult2,sum1);
22
23sumAndMult(1) // 4
24sumAndMultDB(1) // Promise(5)
25```
26#### Pipe
27
28Pipe N functions into another one, also accept functions that a return Promise.
29
30```
31const {pipe} = require('keyu');
32
33const sum1 = x => x+1;
34const mult2 = x => x*2;
35const dbSum = x => Promise.resolve(x+1);
36
37const sumAndMult = pipe(sum1,mult2);
38const sumAndMultDB = pipe(sum1, mult2, dbSum);
39
40sumAndMult(1) // 4
41sumAndMultDB(1) // Promise(5)
42```
43
44### Objects
45
46#### Map
47
48Maps over every key of an object
49```
50let obj = {a:1,b:2,c:3};
51
52console.log(obj.map(value => value+1)) // {a:2}
53console.log(obj.map((value, key) => `${key}:${value+1}`)) // {a:'a:2'}
54```
55
56functional programmming implementation:
57```
58const {map,compose} = require('keyu');
59
60const sum1 = compose(map(x => x+1))
61
62sum1([1]) // [2]
63sum1({a:1}) // {a:2}
64```
65
66#### Filter
67
68Filters an object for each single key
69```
70let obj = {a:1,b:2,c:3};
71
72console.log(obj.filter(value => value > 2)) // {c:3}
73
74console.log(obj.filter((value, key) => value > 1 && key === 'c')) // {c:3}
75```
76
77functional programmming implementation:
78
79```
80const {filter,compose} = require('keyu');
81
82const greaterThan5 = compose(filter(x => x > 5 ))
83
84greaterThan5([1,2,3,4,5,6,7,8]) // [6,7,8]
85greaterThan5({a:1,b:2,c:3,d:4,e:5,f:6,g:7}) // {f:6,g:7}
86```
87
88### Concurrency
89
90#### Any
91
92Promise.all follows a fail-fast pattern meaning that if one single promise fails it stops returning the failure.
93This implements Promise.any which will return the result of all promises independenly if they fail or not.
94
95```
96Promise.any([Promise.resolve(1),Promise.reject(2), Promise.resolve(3)]).then(console.log) // [ { value: 1 }, { error: 2 }, { value: 3 } ]
97```