-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.es6
384 lines (349 loc) · 9.87 KB
/
index.es6
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/**
* Rust-inspired Result<T, E> and Option<T> (called Maybe) wrappers for Javascript.
*
* @author mystor
* @author uniphil
*/
/**
* @throws Error when the match is not exhaustive
* @throws Error when there are weird keys
* @throws Error when `option` is the wrong type for this match
* @param {EnumOption} option The instance to match against
* @param {Object} paths The optionName: callback mapping
* @returns {any} The result of calling the matching callback
*/
function match(option, paths) {
if (!(option instanceof this.OptionClass)) {
if (process.env.NODE_ENV !== 'production' && process) {
console.error(`Not a member from { ${Object.keys(paths).join(', ')} }:`, option);
}
throw new Error(`match called on a non-member option: '${String(option)}'. ` +
`Expected a member from Union{ ${Object.keys(paths).join(', ')} }`);
}
for (let k of Object.keys(paths)) {
if (!option.options.hasOwnProperty(k) && k !== '_') {
throw new Error(`unrecognized match option: '${k}'`);
}
}
if (typeof paths._ === 'function') { // match is de-facto exhaustive w/ `_`
if (typeof paths[option.name] === 'function') {
return paths[option.name](option.payload);
} else {
return paths._(option.payload);
}
} else {
// ensure match is exhaustive
for (let k in option.options) {
if (typeof paths[k] !== 'function') {
if (typeof paths[k] === 'undefined') {
throw new Error(`Non-exhaustive match is missing '${k}'`);
} else {
throw new Error(`match expected a function for '${k}', but found a '${typeof paths[k]}'`);
}
}
}
return paths[option.name](option.payload);
}
}
// Useful in general, but specifically motivated by and inspired by immutablejs
// https://github.com/facebook/immutable-js/blob/master/src/is.js
function _equals(a, b) {
if (a === b || (a !== a && b !== b)) { // true for NaNs
return true;
}
if (!a || !b) {
return false;
}
// There is probably a cleaner way to do this check
// Blame TDD :)
if (a && typeof a.constructor === 'function' &&
a.constructor.unionFactory === Union) {
if (!(b && typeof b.constructor === 'function' &&
b.constructor.unionFactory === Union)) {
return false;
}
if (a.constructor !== b.constructor) {
return false;
}
if (a.name !== b.name) {
return false;
}
return _equals(a.payload, b.payload);
}
// I hate this block. Blame immutablejs :)
if (typeof a.valueOf === 'function' &&
typeof b.valueOf === 'function') {
a = a.valueOf();
b = b.valueOf();
if (a === b || (a !== a && b !== b)) {
return true;
}
if (!a || !b) {
return false;
}
}
if (typeof a.equals === 'function' &&
typeof b.equals === 'function') {
return a.equals(b);
}
return false;
}
function equalsProto(other) {
return _equals(this, other);
}
function hashCode() {
return 42; // TODO: this is valid, but inefficient. Actually implement this :)
}
function unionOptionToString() {
return `[${this.name}(${this.payload}) ` +
`from Union{ ${Object.keys(this.options).join(', ')} }]`;
}
function _factory(options, name, UnionOptionClass) {
return function(payload) {
return new UnionOptionClass(options, name, payload);
};
}
function Union(options, proto={}, static_={}, factory=_factory) {
if (typeof options !== 'object') {
throw new Error('Param `options` must be an object with keys for each member of the union');
}
if (options.hasOwnProperty('toString')) {
throw new Error('Cannot use reserved name `toString` as part of a Union');
}
if (options.hasOwnProperty('match')) {
throw new Error('Cannot use reserved name `match` as part of a Union');
}
if (options.hasOwnProperty('options')) {
throw new UnionError('Cannot use reserved name `options` as part of a Union');
}
if (options.hasOwnProperty('OptionClass')) {
throw new Error('Cannot use reserved name `UnionClass` as part of a Union');
}
for (let k of Object.keys(static_)) {
if (options.hasOwnProperty(k)) {
throw new Error(`Cannot add static method '${k}' to Union which ` +
`has the same name as a member (members: ${options.join(', ')}).`);
}
}
function UnionOption(options, name, payload) {
this.options = options;
this.name = name;
this.payload = payload;
}
UnionOption.prototype.toString = unionOptionToString;
UnionOption.prototype.equals = equalsProto;
UnionOption.prototype.hashCode = hashCode;
Object.keys(proto).forEach(k => UnionOption.prototype[k] = proto[k]);
// put a ref on the union option class back to Union so we can trace things
// back to see if they are from Union
UnionOption.unionFactory = Union;
const union = {
options: options,
OptionClass: UnionOption,
toString: () => `[Union { ${Object.keys(options).join(', ')} }]`,
match,
...static_
};
for (let name of Object.keys(options)) {
union[name] = factory(options, name, UnionOption);
}
return union;
}
// deep-check equality between two union option instances, compatible with immutablejs
Union.is = _equals;
const maybeProto = {
isSome() {
return this.name === 'Some';
},
isNone() {
return this.name === 'None';
},
/**
* @throws Error(msg)
*/
expect(msg) {
if (this.name === 'Some') {
return this.payload;
} else {
throw new Error(msg);
}
},
/**
* @throws Error if it is None
*/
unwrap() {
if (this.name === 'Some') {
return this.payload;
} else {
throw new Error('Tried to .unwrap() Maybe.None as Some');
}
},
unwrapOr(def) {
return (this.name === 'Some') ? this.payload : def;
},
unwrapOrElse(fn) {
return (this.name === 'Some') ? this.payload : fn();
},
okOr(err) {
return (this.name === 'Some') ? Result.Ok(this.payload) : Result.Err(err);
},
okOrElse(errFn) {
return (this.name === 'Some') ? Result.Ok(this.payload) : Result.Err(errFn());
},
promiseOr(err) {
return (this.name === 'Some') ? Promise.resolve(this.payload) : Promise.reject(err);
},
promiseOrElse(fn) {
return (this.name === 'Some') ? Promise.resolve(this.payload) : Promise.reject(fn());
},
and(other) {
return (this.name === 'Some') ? Maybe.Some(other) : this;
},
andThen(fn) {
return (this.name === 'Some') ? Maybe.Some(fn(this.payload)) : this;
},
or(other) {
return (this.name === 'Some') ? this : Maybe.Some(other);
},
orElse(fn) {
return (this.name === 'Some') ? this : Maybe.Some(fn());
},
filter(fn) {
return this.andThen(x => fn(x) ? this : Maybe.None());
}
};
const maybeStatic = {
all: (values) => values.reduce((res, next) =>
res.andThen(resArr => Maybe.Some(next)
.andThen(v => resArr.concat([v])))
, Maybe.Some([])),
undefined: val => (typeof val === 'undefined') ? Maybe.None() : Maybe.Some(val),
null: val => val === null ? Maybe.None() : Maybe.Some(val),
nan: val => (val !== val) ? Maybe.None() : Maybe.Some(val),
};
const Maybe = Union({
Some: null,
None: null,
}, maybeProto, maybeStatic, (options, name, UnionOptionClass) => {
if (name === 'Some') {
return (value) => {
if (value instanceof UnionOptionClass) {
return value;
} else {
return new UnionOptionClass(options, 'Some', value);
}
};
} else { // None
return () => new UnionOptionClass(options, 'None');
}
});
const resultProto = {
isOk() {
return this.name === 'Ok';
},
isErr() {
return this.name === 'Err';
},
ok() {
return (this.name === 'Ok') ? Maybe.Some(this.payload) : Maybe.None();
},
err() {
return (this.name === 'Ok') ? Maybe.None() : Maybe.Some(this.payload);
},
promise() {
return (this.name === 'Ok') ? Promise.resolve(this.payload) : Promise.reject(this.payload);
},
promiseErr() {
return (this.name === 'Ok') ? Promise.reject(this.payload) : Promise.resolve(this.payload);
},
and(other) {
return (this.name === 'Ok') ? Result.Ok(other) : this;
},
andThen(fn) {
return (this.name === 'Ok') ? Result.Ok(fn(this.payload)) : this;
},
or(other) {
return (this.name === 'Ok') ? this : Result.Ok(other);
},
orElse(fn) {
return (this.name === 'Ok') ? this : Result.Ok(fn(this.payload));
},
unwrapOr(def) {
return (this.name === 'Ok') ? this.payload : def;
},
unwrapOrElse(fn) {
return (this.name === 'Ok') ? this.payload : fn(this.payload);
},
/**
* @throws Error(err)
*/
expect(err) {
if (this.name === 'Ok') {
return this.payload;
} else {
throw new Error(err);
}
},
/**
* @throws the value from Err(value)
*/
unwrap() {
if (this.name === 'Ok') {
return this.payload;
} else {
throw this.payload;
}
},
/**
* @throws the value from Ok(value)
*/
unwrapErr() {
if (this.name === 'Ok') {
let hint = '';
if (this.payload && typeof this.payload.toString === 'function') {
hint = `: ${this.payload.toString()}`;
}
throw new Error(`Tried to .unwrap() Result.Ok as Err${hint}`);
} else {
return this.payload;
}
},
};
const resultStatic = {
all: (values) => values.reduce((res, next) =>
res.andThen(resArr => Result.Ok(next)
.andThen(v => resArr.concat([v])))
, Result.Ok([])),
try(maybeThrows) {
try {
return Result.Ok(maybeThrows());
} catch (err) {
return Result.Err(err);
}
},
};
const Result = Union({
Ok: null,
Err: null,
}, resultProto, resultStatic, (options, name, UnionOptionClass) => {
if (name === 'Ok') {
return (value) => {
if (value instanceof UnionOptionClass) {
return value;
} else {
return new UnionOptionClass(options, 'Ok', value);
}
}
} else {
return (err) => new UnionOptionClass(options, 'Err', err);
}
});
module.exports = {
Union,
Maybe,
Some: Maybe.Some,
None: Maybe.None,
Result,
Ok: Result.Ok,
Err: Result.Err,
};