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