Skip to content

Commit 598f22c

Browse files
committed
JavaScript code optimizations
1 parent 6b682ec commit 598f22c

File tree

2 files changed

+34
-23
lines changed

2 files changed

+34
-23
lines changed

JavaScript/maybe4.js

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,29 @@
11
'use strict';
22

3-
function Maybe(x) {
4-
let fn = function(fn) {
5-
if (x && fn) {
6-
return Maybe(fn(x));
7-
} else {
8-
return Maybe(null);
9-
}
10-
}
3+
function maybe(x) {
4+
let map = fn => (x && fn) ? fn(x) : null;
115

12-
fn.ap = maybe => maybe.map(x);
6+
map.ap = map2 => (
7+
maybe(
8+
map(
9+
mbValue => (
10+
maybe(map2)(
11+
mbFunction => mbFunction(mbValue)
12+
)
13+
)
14+
)
15+
)
16+
);
1317

14-
return fn;
18+
return map;
1519
}
1620

17-
Maybe(5)(x => x * 2)(console.log);
18-
Maybe(null)(x => x * 2)(console.log);
21+
maybe(5).ap(x => ++x)(console.log);
22+
maybe(5).ap(x => x * 2).ap(x => ++x)(console.log);
1923

20-
Maybe(x => x * 2).ap(Maybe(5))(console.log);
24+
/*
25+
let a = maybe(7);
26+
let f1 = maybe(x => x * 2);
27+
let f2 = maybe(x => ++x);
28+
a.ap(f1).ap(f2)(console.log);
29+
*/

JavaScript/path.js

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,21 @@
11
'use strict';
22

3-
function Path(data) {
4-
return path => (
5-
Maybe(path)(path => (
3+
global.api = {};
4+
5+
api.fp = {};
6+
7+
api.fp.path = data => (
8+
path => (
9+
api.fp.maybe(path)(path => (
610
path.split('.').reduce(
711
(prev, key) => (prev[key] || {}),
812
(data || {})
913
)
1014
))
11-
);
12-
}
15+
)
16+
);
1317

14-
function Maybe(x) {
15-
return fn => (x && fn) ? Maybe(fn(x)) : Maybe(null);
16-
}
18+
api.fp.maybe = x => fn => api.fp.maybe(x && fn ? fn(x) : null);
1719

1820
// Usage example:
1921

@@ -52,8 +54,8 @@ if (
5254

5355
// Functional style:
5456

55-
Path(config)('server.ssl.key.filename')(
57+
api.fp.path(config)('server.ssl.key.filename')(
5658
file => fs.readFile(file, (err, data) => {
57-
Maybe(data)(console.log);
59+
api.fp.maybe(data)(console.log);
5860
})
5961
);

0 commit comments

Comments
 (0)