Skip to content

Commit 300961d

Browse files
MarcusAureliustshemsedinov
authored andcommitted
Implemented Path(data)(path)(function(value))
1 parent 8450688 commit 300961d

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

JavaScript/path.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
'use strict';
2+
3+
function Path(data) {
4+
return path => (
5+
Maybe(path)(path => (
6+
path.split('.').reduce(
7+
(prev, key) => (prev[key] || {}),
8+
(data || {})
9+
)
10+
))
11+
);
12+
}
13+
14+
function Maybe(x) {
15+
return fn => (x && fn) ? Maybe(fn(x)) : Maybe(null);
16+
}
17+
18+
// Usage example:
19+
20+
const fs = require('fs');
21+
22+
let config = {
23+
server: {
24+
host: {
25+
ip: '10.0.0.1',
26+
port: 3000
27+
},
28+
ssl: {
29+
key: {
30+
filename: './path.js'
31+
}
32+
}
33+
}
34+
};
35+
36+
// Imperative style:
37+
38+
if (
39+
config &&
40+
config.server &&
41+
config.server.ssl &&
42+
config.server.ssl.filename
43+
) {
44+
let fileName = config.server.ssl.filename;
45+
fs.readFile(fileName, (err, data) => {
46+
if (data) {
47+
console.log();
48+
}
49+
});
50+
}
51+
52+
// Functional style:
53+
54+
Path(config)('server.ssl.key.filename')(
55+
file => fs.readFile(file, (err, data) => {
56+
Maybe(data)(console.log);
57+
})
58+
);

0 commit comments

Comments
 (0)