-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathFuture.js
206 lines (176 loc) · 5.49 KB
/
Future.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
var once = require('ramda/src/once');
var forEach = require('ramda/src/forEach');
var toString = require('ramda/src/toString');
var curry = require('ramda/src/curry');
var util = require('./internal/util');
function jail(handler, f){
return function(a){
try{
return f(a);
} catch(err) {
handler(err);
}
};
}
// `f` is a function that takes two function arguments: `reject` (failure) and `resolve` (success)
function Future(f) {
if (!(this instanceof Future)) {
return new Future(f);
}
this._fork = f;
}
Future.prototype['@@type'] = 'ramda-fantasy/Future';
Future.prototype.fork = function(reject, resolve) {
this._fork(reject, jail(reject, resolve));
};
// functor
Future.prototype.map = function(f) {
return this.chain(function(a) { return Future.of(f(a)); });
};
// apply
Future.prototype.ap = function(m) {
var self = this;
return new Future(function(rej, res) {
var applyFn, val;
var doReject = once(rej);
var resolveIfDone = jail(doReject, function() {
if (applyFn != null && val != null) {
return res(applyFn(val));
}
});
self._fork(doReject, function(fn) {
applyFn = fn;
resolveIfDone();
});
m._fork(doReject, function(v) {
val = v;
resolveIfDone();
});
});
};
// applicative
Future.of = function(x) {
// should include a default rejection?
return new Future(function(_, resolve) { return resolve(x); });
};
Future.prototype.of = Future.of;
// chain
// f must be a function which returns a value
// f must return a value of the same Chain
// chain must return a value of the same Chain
//:: Future a, b => (b -> Future c) -> Future c
Future.prototype.chain = function(f) { // Sorella's:
return new Future(function(reject, resolve) {
return this._fork(
function(a) { return reject(a); },
jail(reject, function(b) { return f(b)._fork(reject, resolve); })
);
}.bind(this));
};
// chainRec
//
// Heavily influenced by the Aff MonadRec instance
// https://github.com/slamdata/purescript-aff/blob/51106474122d0e5aec8e3d5da5bb66cfe8062f55/src/Control/Monad/Aff.js#L263-L322
Future.chainRec = Future.prototype.chainRec = function(f, a) {
return Future(function(reject, resolve) {
return function go(acc) {
// isSync could be in three possable states
// * null - unresolved status
// * true - synchronous future
// * false - asynchronous future
var isSync = null;
var state = util.chainRecNext(acc);
var onResolve = function(v) {
// If the `isSync` is still unresolved, we have observed a
// synchronous future. Otherwise, `isSync` will be `false`.
if (isSync === null) {
isSync = true;
// Store the result for further synchronous processing.
state = v;
} else {
// When we have observed an asynchronous future, we use normal
// recursion. This is safe because we will be on a new stack.
(v.isNext ? go : resolve)(v.value);
}
};
while (state.isNext) {
isSync = null;
f(util.chainRecNext, util.chainRecDone, state.value).fork(reject, onResolve);
// If the `isSync` has already resolved to `true` by our `onResolve`, then
// we have observed a synchronous future. Otherwise it will still be `null`.
if (isSync === true) {
continue;
} else {
// If the status has not resolved yet, then we have observed an
// asynchronous or failed future so update status and exit the loop.
isSync = false;
return;
}
}
resolve(state.value);
}(a);
});
};
// chainReject
// Like chain but operates on the reject instead of the resolve case.
//:: Future a, b => (a -> Future c) -> Future c
Future.prototype.chainReject = function(f) {
return new Future(function(reject, resolve) {
return this._fork(
jail(reject, function(a) { return f(a)._fork(reject, resolve); }),
function(b) { return resolve(b); }
);
}.bind(this));
};
// monad
// A value that implements the Monad specification must also implement the Applicative and Chain specifications.
// see above.
Future.prototype.bimap = function(errFn, successFn) {
var self = this;
return new Future(function(reject, resolve) {
self._fork(
jail(reject, function(err) { reject(errFn(err)); }),
jail(reject, function(val) { resolve(successFn(val)); })
);
});
};
Future.reject = function(val) {
return new Future(function(reject) {
reject(val);
});
};
Future.prototype.toString = function() {
return 'Future(' + toString(this._fork) + ')';
};
Future.cache = function(f) {
var status = 'IDLE';
var listeners = [];
var cachedValue;
var handleCompletion = curry(function(newStatus, cb, val) {
status = newStatus;
cachedValue = val;
cb(val);
forEach(function(listener) {
listener[status](cachedValue);
}, listeners);
});
function addListeners(reject, resolve) {
listeners.push({ REJECTED: reject, RESOLVED: resolve } );
}
function doResolve(reject, resolve) {
status = 'PENDING';
return f._fork(
handleCompletion('REJECTED', reject),
handleCompletion('RESOLVED', resolve)
);
}
return new Future(function(reject, resolve) {
switch(status) {
case 'IDLE': doResolve(reject, resolve); break;
case 'PENDING': addListeners(reject, resolve); break;
case 'REJECTED': reject(cachedValue); break;
case 'RESOLVED': resolve(cachedValue); break;
}
});
};
module.exports = Future;