-
Notifications
You must be signed in to change notification settings - Fork 6
/
classic_result.ts
547 lines (495 loc) · 17 KB
/
classic_result.ts
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
import {
type ClassicOption,
type ClassicSome as Some,
type ClassicNone as None,
createClassicSome,
createClassicNone,
} from '../classic_option/classic_option.js';
import type { TransformFn, RecoveryFromErrorFn, EffectFn } from '../internal/function.js';
/**
* @deprecated
* See https://github.com/option-t/option-t/issues/459
*/
export type ClassicTryTransformFn<T, U, E> = TransformFn<T, ClassicResult<U, E>>;
/**
* @deprecated
* See https://github.com/option-t/option-t/issues/459
*/
export type ClassicTryRecoverFromErrorFn<T, E, F> = RecoveryFromErrorFn<E, ClassicResult<T, F>>;
/**
* @deprecated
* We keep this only for backward compatibility.
* See https://github.com/option-t/option-t/issues/459
*/
interface ClassicResultable<T, E> {
/**
* Returns true if the result is `Ok`.
*/
isOk(): this is ClassicOk<T, E>;
/**
* Returns true if the result is `Err`.
*/
isErr(): this is ClassicErr<T, E>;
/**
* Converts from `Result<T, E>` to `Option<T>`.
* If the self is `Ok`, returns `Some<T>`.
* Otherwise, returns `None<T>`.
*/
ok(): ClassicOption<T>;
/**
* Converts from `Result<T, E>` to `Option<E>`.
* If the self is `Err`, returns `Some<E>`.
* Otherwise, returns `None<E>`.
*/
err(): ClassicOption<E>;
/**
* Maps a `Result<T, E>` to `Result<U, E>` by applying a function `mapFn<T, U>`
* to an contained `Ok` value, leaving an `Err` value untouched.
*
* This function can be used to compose the results of two functions.
*/
map<U>(op: TransformFn<T, U>): ClassicResult<U, E>;
/**
* Maps a `Result<T, E>` to `U` by applying a function to a contained `Ok` value,
* or a `fallback` function to a contained `Err` value.
* This function can be used to unpack a successful result while handling an error.
*/
mapOrElse<U>(fallback: RecoveryFromErrorFn<E, U>, selector: TransformFn<T, U>): U;
/**
* Maps a `Result<T, E>` to `Result<T, F>` by applying a function `mapFn<E, F>`
* to an contained `Err` value, leaving an `Ok` value untouched.
*
* This function can be used to pass through a successful result while handling an error.
*/
mapErr<F>(op: TransformFn<E, F>): ClassicResult<T, F>;
/**
* Returns `res` if the result is `Ok`, otherwise returns the `Err` value of self.
*/
and<U>(res: ClassicResult<U, E>): ClassicResult<U, E>;
/**
* Calls `op` if the result is `Ok`, otherwise returns the `Err` value of self.
* This function can be used for control flow based on result values.
*/
andThen<U>(op: ClassicTryTransformFn<T, U, E>): ClassicResult<U, E>;
/**
* Returns `res` if the result is `Err`, otherwise returns the `Ok` value of self.
*/
or<F>(res: ClassicResult<T, F>): ClassicResult<T, F>;
/**
* Calls `op` if the result is `Err`, otherwise returns the `Ok` value of self.
* This function can be used for control flow based on result values.
*/
orElse<F>(op: ClassicTryRecoverFromErrorFn<T, E, F>): ClassicResult<T, F>;
/**
* Return the inner `T` of a `Ok(T)`.
*
* @throws {Error}
* Throws if the self is a `Err`.
*/
unwrap(): T | never;
/**
* Return the inner `E` of a `Err(E)`.
*
* @throws {Error}
* Throws if the self is a `Ok`.
*/
unwrapErr(): E | never;
/**
* Unwraps a result, return the content of an `Ok`. Else it returns `optb`.
*/
unwrapOr(optb: T): T;
/**
* Unwraps a result, returns the content of an `Ok`.
* If the value is an `Err` then it calls `op` with its value.
*/
unwrapOrElse(op: RecoveryFromErrorFn<E, T>): T;
/**
* Return the inner `T` of a `Ok(T)`.
*
* @throws {Error}
* Throws the passed `message` if the self is a `Err`.
*/
expect(message: string): T | never;
/**
* The destructor method inspired by Rust's `Drop` trait.
* We don't define the object's behavior after calling this.
*
* @param destructor
* This would be called with the inner value if self is `Ok<T>`.
* @param errDestructor
* This would be called with the inner value if self is `Err<E>`.
*/
drop(destructor?: EffectFn<T>, errDestructor?: EffectFn<E>): void;
}
/**
* @deprecated
* See https://github.com/option-t/option-t/issues/459
*
* XXX:
* This is only used for the instanceof-basis runtime checking. (e.g. `React.PropTypes.instanceOf()`)
* You MUST NOT use for other purpose.
*/
export abstract class ClassicResultBase<T, E> implements ClassicResultable<T, E> {
private readonly _isOk: boolean;
private readonly _v: T | undefined;
private readonly _e: E | undefined;
protected constructor(ok: boolean, val: T | undefined, err: E | undefined) {
this._isOk = ok;
this._v = val;
this._e = err;
Object.seal(this);
}
/**
* Returns true if the result is `Ok`.
*/
isOk(): this is ClassicOk<T, E> {
return this._isOk;
}
/**
* Returns true if the result is `Err`.
*/
isErr(): this is ClassicErr<T, E> {
return !this._isOk;
}
/**
* Converts from `Result<T, E>` to `Option<T>`.
* If the self is `Ok`, returns `Some<T>`.
* Otherwise, returns `None<T>`.
*
* @return {!OptionT<T>}
*/
ok(): ClassicOption<T> {
if (this._isOk) {
// This code is required to keep backward compatibility.
// @ts-expect-error
return createClassicSome(this._v);
} else {
return createClassicNone<T>();
}
}
/**
* Converts from `Result<T, E>` to `Option<E>`.
* If the self is `Err`, returns `Some<E>`.
* Otherwise, returns `None<E>`.
*
* @return {!OptionT<E>}
*/
err(): ClassicOption<E> {
if (!this._isOk) {
// This code is required to keep backward compatibility.
// @ts-expect-error
return createClassicSome(this._e);
} else {
return createClassicNone();
}
}
/**
* Maps a `Result<T, E>` to `Result<U, E>` by applying a function `mapFn<T, U>`
* to an contained `Ok` value, leaving an `Err` value untouched.
*
* This function can be used to compose the results of two functions.
*/
map<U>(op: TransformFn<T, U>): ClassicResult<U, E> {
if (!this._isOk) {
// cheat to escape from a needless allocation.
// @ts-expect-error
return this;
}
// This code is required to keep backward compatibility.
// @ts-expect-error
const value = op(this._v);
const result = createClassicOk<U, E>(value);
return result;
}
/**
* Maps a `Result<T, E>` to `U` by applying a function to a contained `Ok` value,
* or a `fallback` function to a contained `Err` value.
* This function can be used to unpack a successful result while handling an error.
*/
mapOrElse<U>(fallback: RecoveryFromErrorFn<E, U>, selector: TransformFn<T, U>): U {
if (!this._isOk) {
// This code is required to keep backward compatibility.
// @ts-expect-error
const r = fallback(this._e);
return r;
}
// This code is required to keep backward compatibility.
// @ts-expect-error
const r = selector(this._v);
return r;
}
/**
* Maps a `Result<T, E>` to `Result<T, F>` by applying a function `mapFn<E, F>`
* to an contained `Err` value, leaving an `Ok` value untouched.
*
* This function can be used to pass through a successful result while handling an error.
*/
mapErr<F>(op: TransformFn<E, F>): ClassicResult<T, F> {
if (this._isOk) {
// cheat to escape from a needless allocation.
// @ts-expect-error
return this;
}
// This code is required to keep backward compatibility.
// @ts-expect-error
const value = op(this._e);
const result = createClassicErr<T, F>(value);
return result;
}
/**
* Returns `res` if the result is `Ok`, otherwise returns the `Err` value of self.
*/
and<U>(res: ClassicResult<U, E>): ClassicResult<U, E> {
if (this._isOk) {
return res;
} else {
// cheat to escape from a needless allocation.
// @ts-expect-error
return this;
}
}
/**
* Calls `op` if the result is `Ok`, otherwise returns the `Err` value of self.
* This function can be used for control flow based on result values.
*/
andThen<U>(op: ClassicTryTransformFn<T, U, E>): ClassicResult<U, E> {
if (!this._isOk) {
// cheat to escape from a needless allocation.
// @ts-expect-error
return this;
}
// This code is required to keep backward compatibility.
// @ts-expect-error
const mapped = op(this._v);
const isResult = mapped instanceof ClassicResultBase;
if (!isResult) {
throw new TypeError("Result<T, E>.andThen()' param `op` should return `Result<U, E>`.");
}
return mapped;
}
/**
* Returns `res` if the result is `Err`, otherwise returns the `Ok` value of self.
*/
or<F>(res: ClassicResult<T, F>): ClassicResult<T, F> {
if (this._isOk) {
// cheat to escape from a needless allocation.
// @ts-expect-error
return this;
} else {
return res;
}
}
/**
* Calls `op` if the result is `Err`, otherwise returns the `Ok` value of self.
* This function can be used for control flow based on result values.
*/
orElse<F>(op: ClassicTryRecoverFromErrorFn<T, E, F>): ClassicResult<T, F> {
if (this._isOk) {
// cheat to escape from a needless allocation.
// @ts-expect-error
return this;
}
// This code is required to keep backward compatibility.
// @ts-expect-error
const mapped = op(this._e);
const isResult = mapped instanceof ClassicResultBase;
if (!isResult) {
throw new TypeError("Result<T, E>.orElse()' param `op` should return `Result<T, F>`.");
}
return mapped;
}
/**
* Return the inner `T` of a `Ok(T)`.
*
* @throws {TypeError}
* Throws if the self is a `Err`.
*/
unwrap(): T | never {
return this.expect('called `unwrap()` on a `Err` value');
}
/**
* Return the inner `E` of a `Err(E)`.
*
* @throws {TypeError}
* Throws if the self is a `Ok`.
*/
unwrapErr(): E | never {
if (this._isOk) {
throw new TypeError('called `unwrapErr()` on a `Ok` value');
} else {
// This code is required to keep backward compatibility.
// @ts-expect-error
return this._e;
}
}
/**
* Unwraps a result, return the content of an `Ok`. Else it returns `optb`.
*/
unwrapOr(optb: T): T {
if (this._isOk) {
// This code is required to keep backward compatibility.
// @ts-expect-error
return this._v;
} else {
return optb;
}
}
/**
* Unwraps a result, returns the content of an `Ok`.
* If the value is an `Err` then it calls `op` with its value.
*/
unwrapOrElse(op: RecoveryFromErrorFn<E, T>): T {
if (this._isOk) {
// This code is required to keep backward compatibility.
// @ts-expect-error
return this._v;
}
// This code is required to keep backward compatibility.
// @ts-expect-error
const recovered = op(this._e);
return recovered;
}
/**
* Return the inner `T` of a `Ok(T)`.
*
* @throws {TypeError}
* Throws the passed `message` if the self is a `Err`.
*/
expect(message: string): T | never {
if (this._isOk) {
// This code is required to keep backward compatibility.
// @ts-expect-error
return this._v;
} else {
throw new TypeError(message);
}
}
/**
* The destructor method inspired by Rust's `Drop` trait.
* We don't define the object's behavior after calling this.
*
* @param destructor
* This would be called with the inner value if self is `Ok<T>`.
* @param errDestructor
* This would be called with the inner value if self is `Err<E>`.
*/
drop(destructor?: EffectFn<T>, errDestructor?: EffectFn<E>): void {
if (this._isOk) {
if (typeof destructor === 'function') {
// This code is required to keep backward compatibility.
// @ts-expect-error
destructor(this._v);
}
// This code is required to keep backward compatibility.
// @ts-expect-error
this._v = null;
} else {
if (typeof errDestructor === 'function') {
// This code is required to keep backward compatibility.
// @ts-expect-error
errDestructor(this._e);
}
// This code is required to keep backward compatibility.
// @ts-expect-error
this._e = null;
}
Object.freeze(this);
}
}
Object.freeze(ClassicResultBase.prototype);
/**
* @deprecated
* We keep this only for backward compatibility.
* See https://github.com/option-t/option-t/issues/459
*/
interface ClassicOk<T, E> extends ClassicResultable<T, E> {
ok(): Some<T>;
err(): None<E>;
unwrap(): T;
unwrapErr(): never;
unwrapOr(optb: T): T;
expect(message: string): T;
}
/**
* @deprecated
* We keep this only for backward compatibility.
* See https://github.com/option-t/option-t/issues/459
*
* XXX:
* This class intend to represent the container of some error type `E`.
* So we don't define this as `Error`'s subclass
* or don't restrict type parameter `E`'s upper bound to `Error`.
*/
interface ClassicErr<T, E> extends ClassicResultable<T, E> {
ok(): None<T>;
err(): Some<E>;
unwrap(): never;
unwrapErr(): E;
expect(message: string): never;
}
/**
* @deprecated
* See https://github.com/option-t/option-t/issues/459
*
* The Result/Either type interface whose APIs are inspired
* by Rust's `std::result::Result<T, E>`.
*
* _We recommend to use utility types & functions (`PlainResult/Result<T, E>`)
* if you don't have to use `instanceof` check and
* you should avoid to expose this object as a public API of your package_
* because `instanceof` checking might not work correctly if a user project has
* multiple version of this package in their dependencies.
* See ([#337](https://github.com/option-t/option-t/pull/337)).
*
* Furthermore, we don't have a plan to implements a new API aggressively for this object
* because we need to implement it on `.prototype`
* and it might be hard to remove unused methods from `.prototype` on minifying.
* We could resolve this problem for the future release but today is not so.
*
* See [#378](https://github.com/option-t/option-t/issues/378)
*
* And some operators might not return a new object and reuse the input
* to reduce an object allocation. Thus comparing _this `Option<T>`` is meaningles.
* This is by design because we think this pattern is meaningless.
*/
export type ClassicResult<T, E> = ClassicOk<T, E> | ClassicErr<T, E>;
/**
* @deprecated
* See https://github.com/option-t/option-t/issues/459
*/
export function createClassicOk<T, E>(val: T): ClassicOk<T, E> {
// This code is required to keep backward compatibility.
// @ts-expect-error
const o = new ClassicResultBase<T, E>(true, val, undefined);
return o;
}
/**
* @deprecated
* See https://github.com/option-t/option-t/issues/459
*/
export function createClassicErr<T, E>(err: E): ClassicErr<T, E> {
// This code is required to keep backward compatibility.
// @ts-expect-error
const o = new ClassicResultBase<T, E>(false, undefined, err);
return o;
}
/**
* @deprecated
* See https://github.com/option-t/option-t/issues/459
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
export const ClassicOkConstructor: new <T, E>(val: T) => ClassicOk<T, E> =
function ClassicOkConstructor<T, E>(val: T) {
return createClassicOk<T, E>(val);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any;
/**
* @deprecated
* See https://github.com/option-t/option-t/issues/459
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
export const ClassicErrConstructor: new <T, E>(err: E) => ClassicErr<T, E> =
function ClassicErrConstructor<T, E>(err: E) {
return createClassicErr<T, E>(err);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any;