-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathIO.js
66 lines (53 loc) · 1.39 KB
/
IO.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
var compose = require('ramda/src/compose');
var toString = require('ramda/src/toString');
var util = require('./internal/util');
module.exports = IO;
function IO(fn) {
if (!(this instanceof IO)) {
return new IO(fn);
}
this.fn = fn;
}
IO.prototype['@@type'] = 'ramda-fantasy/IO';
// `f` must return an IO
IO.prototype.chain = function(f) {
var io = this;
return new IO(function() {
var next = f(io.fn.apply(io, arguments));
return next.fn.apply(next, arguments);
});
};
//chainRec
IO.chainRec = IO.prototype.chainRec = function(f, i) {
return new IO(function() {
var state = util.chainRecNext(i);
while (state.isNext) {
state = f(util.chainRecNext, util.chainRecDone, state.value).fn();
}
return state.value;
});
};
IO.prototype.map = function(f) {
var io = this;
return new IO(compose(f, io.fn));
};
// `this` IO must wrap a function `f` that takes an IO (`thatIo`) as input
// `f` must return an IO
IO.prototype.ap = function(thatIo) {
return this.chain(function(f) {
return thatIo.map(f);
});
};
IO.runIO = function(io) {
return io.runIO.apply(io, [].slice.call(arguments, 1));
};
IO.prototype.runIO = function() {
return this.fn.apply(this, arguments);
};
IO.prototype.of = function(x) {
return new IO(function() { return x; });
};
IO.of = IO.prototype.of;
IO.prototype.toString = function() {
return 'IO(' + toString(this.fn) + ')';
};