-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
276 lines (239 loc) · 7.75 KB
/
index.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
//. # Fluture Hooks
//.
//. Fantasy Land Monad and Alternative instances for return values from
//. [Fluture's `hook`][hook].
//.
//. [hook]: https://github.com/fluture-js/Fluture#hook
//.
//. ## Usage
//.
//. ### Node
//.
//. ```console
//. $ npm install --save fluture-hooks
//. ```
//.
//. On Node 12 and up, this module can be loaded directly with `import` or
//. `require`. On Node versions below 12, `require` or the [esm][]-loader can
//. be used.
//.
//. ### Deno and Modern Browsers
//.
//. You can load the EcmaScript module from various content delivery networks:
//.
//. - [Skypack](https://cdn.skypack.dev/[email protected])
//. - [JSPM](https://jspm.dev/[email protected])
//. - [jsDelivr](https://cdn.jsdelivr.net/npm/[email protected]/+esm)
//.
//. ### Old Browsers and Code Pens
//.
//. There's a [UMD][] file included in the NPM package, also available via
//. jsDelivr: https://cdn.jsdelivr.net/npm/[email protected]/dist/umd.js
//.
//. This file adds `flutureHooks` to the global scope, or use CommonJS/AMD
//. when available.
//.
//. ### Usage Example
//.
//. ```js
//. import {Future, node, fork} from 'fluture/index.js';
//. import {hook, hookAll, runHook} from 'fluture-hooks/index.js';
//.
//. const acquirePostgres = (
//. node (done => require ('imaginary-postgres').connect (done))
//. );
//.
//. const acquireRedis = (
//. node (done => require ('imaginary-redis').connect (done))
//. );
//.
//. const closeConnection = connection => (
//. node (done => connection.end (done))
//. );
//.
//. const postgresHook = hook (acquirePostgres) (closeConnection);
//. const redisHook = hook (acquireRedis) (closeConnection);
//. const servicesHook = hookAll ([postgresHook, redisHook]);
//.
//. const withServices = runHook (servicesHook);
//.
//. fork (console.error)
//. (console.log)
//. (withServices (([postgres, redis]) => Future ((rej, res) => {
//. /* consume postgres and redis */
//. })));
//. ```
import * as Callback from 'callgebra/index.js';
import {
Future,
ap,
cache,
chain,
hook as asyncHook,
map,
never,
} from 'fluture/index.js';
const $of = 'fantasy-land/of';
const $ap = 'fantasy-land/ap';
const $map = 'fantasy-land/map';
const $chain = 'fantasy-land/chain';
const pure = T => x => T[$of] (x);
const lift2 = f => a => b => ap (b) (map (f) (a));
const append = xs => x => xs.concat ([x]);
const mappend = lift2 (append);
function HookFromCallback(run) {
if (typeof run !== 'function') {
throw new TypeError ('Function expected');
}
this.run = run;
}
function ParallelHookFromHook(hook) {
if (!(hook instanceof Hook)) {
throw new TypeError ('Hook expected');
}
this.hook = hook;
}
//. ## API
//.
//# Hook :: ((b -> a) -> a) -> Hook a b
//.
//. Tags a function awaiting a callback (such as the value returned by
//. [Fluture's `hook`][hook]) as a "Hook".
//.
//. `Hook a` has Monad instance with sequential behaviour in its Applicative.
//.
//. ```js
//. Hook (Future.hook (myResourceAcquisition) (myResourceDisposal));
//. ```
export function Hook(run) {
return new HookFromCallback (run);
}
HookFromCallback.prototype = Object.create (Hook.prototype);
Hook['@@type'] = 'fluture/Hook@1';
Hook.constructor = {prototype: Hook};
Hook.of = Hook[$of] = x => Hook (Callback.of (x));
Hook.prototype['@@type'] = Hook['@@type'];
Hook.prototype[$ap] = function(mf) {
return Hook (Callback.ap (mf.run) (this.run));
};
Hook.prototype[$map] = function(f) {
return Hook (Callback.map (f) (this.run));
};
Hook.prototype[$chain] = function(f) {
return Hook (Callback.chain (x => f (x).run) (this.run));
};
//# hook :: Future a b -> (b -> Future c d) -> Hook (Future a e) b
//.
//. `hook (m) (f)` is the equivalent of `Hook (Future.hook (m) (f))`.
export const hook = m => f => Hook (asyncHook (m) (f));
//# acquire :: Future a b -> Hook (Future a d) b
//.
//. Creates a Hook without the need for a disposal function.
export const acquire = m => Hook (f => chain (f) (m));
//# runHook :: Hook b a -> (a -> b) -> b
//.
//. Given a Hook and a callback, runs the Hook, returning the callbacks' return
//. value. For Hooks created from Fluture's hook, this means a Future is
//. retured.
//.
//. This function can also be thought of as "untagging" a [`Hook`](#Hook):
//. `runHook (Hook (h)) = h`.
export const runHook = hook => hook.run;
//# ParallelHook :: Hook a b -> ParallelHook a b
//.
//. Construct a ParallelHook using a Hook.
//.
//. `ParallelHook a` has a Functor instance, and `ParallelHook (Future a b)`
//. has an Applicative instance with parallel behaviour.
export function ParallelHook(hook) {
return new ParallelHookFromHook (hook);
}
ParallelHookFromHook.prototype = Object.create (ParallelHook.prototype);
ParallelHook['@@type'] = 'fluture/ParallelHook@1';
ParallelHook.constructor = {prototype: ParallelHook};
ParallelHook.of = ParallelHook[$of] = x => ParallelHook (pure (Hook) (x));
ParallelHook.prototype['@@type'] = ParallelHook['@@type'];
ParallelHook.prototype[$map] = function(f) {
return ParallelHook (map (f) (this.hook));
};
function CustomFuture(interpret) {
this._interpret = interpret;
}
CustomFuture.prototype = Object.create (Future.prototype);
ParallelHook.prototype[$ap] = function(parallelFunctionHook) {
const withValue = runHook (sequential (this));
const withFunction = runHook (sequential (parallelFunctionHook));
return ParallelHook (Hook (callback => new CustomFuture ((rec, rej, res) => {
let deferred = null;
let cont = null;
let cancelled = false;
let cancelValue = null;
let cancelFunction = null;
const defer = value => {
deferred = cache (never);
deferred.value = value;
return deferred;
};
const consume = resource => new CustomFuture ((rec, rej, res) => (
callback (resource)._interpret (x => { rec (x); deferred.crash (x); }
, x => { rej (x); deferred.reject (x); }
, x => { res (x); deferred.resolve (x); })
));
const eventuallyConsumeValue = withValue (val => (
deferred ? consume (deferred.value (val)) : defer (val)
));
const eventuallyConsumeFunction = withFunction (func => (
deferred ? consume (func (deferred.value)) : defer (func)
));
/* c8 ignore next 3 */
const crash = x => {
cancel ();
rec (x);
};
const reject = x => {
if (cont != null) { rej (x); } else if (deferred == null) {
cancel ();
rej (x);
} else {
/* c8 ignore next */
cont = () => rej (x);
deferred.reject (x);
}
};
const resolve = x => {
if (cont != null) cont ();
else cont = () => res (x);
};
cancelValue = eventuallyConsumeValue._interpret (crash, reject, resolve);
cancelFunction = (
cancelled ?
null :
eventuallyConsumeFunction._interpret (crash, reject, resolve)
);
function cancel() {
if (cancelled) return;
cancelled = true;
cancelValue && cancelValue ();
cancelFunction && cancelFunction ();
}
return cancel;
})));
};
//# sequential :: ParallelHook a b -> Hook a b
//.
//. Converts a ParallelHook to a normal Hook.
export const sequential = m => m.hook;
const hookAllReducer = (xs, x) => mappend (xs) (x);
//# hookAll :: Array (Hook (Future a b) c) -> Hook (Future a b) (Array c)
//.
//. Combines resources from many hooks into a single hook in parallel, given
//. that the eventual consumption of this new hook will return a Future.
//.
//. `hookAll (hooks)` is the equivalent of
//. `sequential (sequence (ParallelHook) (map (ParallelHook) (hooks)))` for all
//. `hooks :: Array (Hook (Future a b) c)`.
export const hookAll = xs => sequential (
xs.map (ParallelHook).reduce (hookAllReducer, pure (ParallelHook) ([]))
);
//. [esm]: https://github.com/standard-things/esm
//. [UMD]: https://github.com/umdjs/umd