Skip to content

Commit c36cf20

Browse files
committed
Implemented Maybe.ap() and fixed Maybe.map in JavaScript example
1 parent 0affa78 commit c36cf20

File tree

1 file changed

+7
-9
lines changed

1 file changed

+7
-9
lines changed

JavaScript/maybe3.js

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,16 @@ function Maybe(x) {
55
}
66

77
Maybe.prototype.map = function(fn) {
8-
if (this.x && fn) {
9-
return new Maybe(fn(this.x));
10-
} else {
11-
return new Maybe(null);
12-
}
8+
return (this.x && fn) ? fn(this.x) : null;
139
};
1410

1511
Maybe.prototype.ap = function(maybe) {
16-
return maybe.map(this.x);
12+
return new Maybe(this.map(mbValue => (maybe.map(
13+
mbFunction => mbFunction(mbValue)
14+
))));
1715
};
1816

1917
let a = new Maybe(5);
20-
let b = new Maybe(x => x * 2);
21-
let c = b.ap(a).map(console.log);
22-
console.log(c);
18+
let f1 = new Maybe(x => x * 2);
19+
let f2 = new Maybe(x => ++x);
20+
a.ap(f1).ap(f2).map(console.log);

0 commit comments

Comments
 (0)