Skip to content

Commit cdb2bb0

Browse files
committed
Optimize JavaScript examples
1 parent 0bf92d2 commit cdb2bb0

File tree

7 files changed

+45
-10
lines changed

7 files changed

+45
-10
lines changed

Haskell/maybe.hs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ data Maybe a = Just a | Nothing
55

66
class Functor f where
77
fmap :: (a -> b) -> f a -> f b
8-
8+
99
(<$>) :: Functor f => (a -> b) -> f a -> f b
1010
(<$>) = fmap
1111
infixl 4 <$>

Haskell/maybe3.hs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,3 @@ main = do
2020
b = Just $ (* 2) . (+ 5) . (^ 2)
2121
c = b <*> a
2222
print c
23-
24-
File renamed without changes.

JavaScript/maybe11.js

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

JavaScript/maybe21.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
'use strict';
2+
3+
let Maybe = x => fn => (x && fn) ? Maybe(fn(x)) : Maybe(null);
4+
5+
Maybe(5)(x => x * 2)(console.log);
6+
Maybe(null)(x => x * 2)(console.log);

JavaScript/maybe3.js

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
'use strict';
2+
13
function Maybe(x) {
24
this.x = x;
35
}
@@ -8,16 +10,13 @@ Maybe.prototype.map = function(fn) {
810
} else {
911
return new Maybe(null);
1012
}
11-
}
13+
};
1214

1315
Maybe.prototype.ap = function(maybe) {
14-
if (maybe) {
15-
return maybe.map(this.x);
16-
} else {
17-
return new Maybe(null);
18-
}
19-
}
16+
return maybe.map(this.x);
17+
};
2018

2119
let a = new Maybe(5);
2220
let b = new Maybe(x => x * 2);
2321
let c = b.ap(a).map(console.log);
22+
console.log(c);

JavaScript/maybe4.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
'use strict';
2+
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+
}
11+
12+
fn.ap = maybe => maybe.map(x);
13+
14+
return fn;
15+
}
16+
17+
Maybe(5)(x => x * 2)(console.log);
18+
Maybe(null)(x => x * 2)(console.log);
19+
20+
Maybe(x => x * 2).ap(Maybe(5))(console.log);

0 commit comments

Comments
 (0)