-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy path8-path.js
63 lines (52 loc) · 1.07 KB
/
8-path.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
'use strict';
const fp = {};
fp.path = (data) => (
(path) => (
fp.maybe(path)((path) => (
path.split('.').reduce(
(prev, key) => (prev[key] || {}),
(data || {})
)
))
)
);
fp.isJust = (value) => {
if (!value || typeof value !== 'object') return Boolean(value);
if (Object.keys(value).length === 0) return false;
return true;
};
fp.maybe = (x) => (fn) => fp.maybe(fp.isJust(x) && fn ? fn(x) : null);
// Usage
const fs = require('node:fs');
const config = {
server: {
host: {
ip: '10.0.0.1',
port: 3000
},
ssl: {
key: {
filename: './7-path.js'
}
}
}
};
// Imperative style
if (
config &&
config.server &&
config.server.ssl &&
config.server.ssl.key &&
config.server.ssl.key.filename
) {
const fileName = config.server.ssl.key.filename;
fs.readFile(fileName, 'utf8', (err, data) => {
if (data) console.log();
});
}
// Functional style
fp.path(config)('server.ssl.key.filename')(
(file) => fs.readFile(file, 'utf8', (err, data) => {
fp.maybe(data)(console.log);
})
);