Skip to content

Commit 8450688

Browse files
author
MarcusAurelius
committed
Added 3 JavaScript maybe implementations
1 parent a646f62 commit 8450688

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

JavaScript/maybe.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
function Maybe(x) {
2+
this.x = x;
3+
}
4+
5+
Maybe.prototype.map = function(fn) {
6+
if (this.x && fn) {
7+
return new Maybe(fn(this.x));
8+
} else {
9+
return new Maybe(null);
10+
}
11+
}
12+
13+
new Maybe(5).map(x => x * 2).map(console.log);
14+
new Maybe(null).map(x => x * 2).map(console.log);

JavaScript/maybe2.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
function Maybe(x) {
2+
return function(fn) {
3+
if (x && fn) {
4+
return Maybe(fn(x));
5+
} else {
6+
return Maybe(null);
7+
}
8+
};
9+
}
10+
11+
Maybe(5)(x => x * 2)(console.log);
12+
Maybe(null)(x => x * 2)(console.log);

JavaScript/maybe3.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
function Maybe(x) {
2+
this.x = x;
3+
}
4+
5+
Maybe.prototype.map = function(fn) {
6+
if (this.x && fn) {
7+
return new Maybe(fn(this.x));
8+
} else {
9+
return new Maybe(null);
10+
}
11+
}
12+
13+
Maybe.prototype.ap = function(maybe) {
14+
if (maybe) {
15+
return maybe.map(this.x);
16+
} else {
17+
return new Maybe(null);
18+
}
19+
}
20+
21+
let a = new Maybe(5);
22+
let b = new Maybe(x => x * 2);
23+
let c = b.ap(a).map(console.log);

0 commit comments

Comments
 (0)