import { Future } from './Future'; import { Result } from './Result'; export interface FutureResult extends Future> { readonly toCached: () => FutureResult; readonly bindFuture: (f: (value: A) => Future>) => FutureResult; readonly bindResult: (f: (value: A) => Result) => FutureResult; readonly mapResult: (f: (value: A) => B) => FutureResult; readonly mapError: (f: (error: E) => B) => FutureResult; readonly foldResult: (whenError: (error: E) => X, whenValue: (value: A) => X) => Future; readonly withTimeout: (timeout: number, errorThunk: () => E) => FutureResult; } const wrap = (delegate: Future>): FutureResult => { const toCached = () => { return wrap(delegate.toCached()); }; const bindFuture = (f: (value: A) => Future>) => { return wrap( delegate.bind( (resA) => resA.fold( (err: E) => (Future.pure(Result.error(err))), (a: A) => f(a) ) ) ); }; const bindResult = (f: (value: A) => Result) => { return wrap(delegate.map((resA) => resA.bind(f))); }; const mapResult = (f: (value: A) => B) => { return wrap(delegate.map((resA) => resA.map(f))); }; const mapError = (f: (error: E) => B) => { return wrap(delegate.map((resA) => resA.mapError(f))); }; const foldResult = (whenError: (error: E) => X, whenValue: (value: A) => X) => { return delegate.map((res) => res.fold(whenError, whenValue)); }; const withTimeout = (timeout: number, errorThunk: () => E) => { return wrap(Future.nu((callback: (value: Result) => void) => { let timedOut = false; const timer = setTimeout(() => { timedOut = true; callback(Result.error(errorThunk())); }, timeout); delegate.get((result) => { if (!timedOut) { clearTimeout(timer); callback(result); } }); })); }; return { ...delegate, toCached, bindFuture, bindResult, mapResult, mapError, foldResult, withTimeout }; }; const nu = (worker: (completer: (result: Result) => void) => void): FutureResult => { return wrap(Future.nu(worker)); }; const value = (value: A): FutureResult => { return wrap(Future.pure(Result.value(value))); }; const error = (error: E): FutureResult => { return wrap(Future.pure(Result.error(error))); }; const fromResult = (result: Result): FutureResult => { return wrap(Future.pure(result)); }; const fromFuture = (future: Future): FutureResult => { return wrap(future.map(Result.value)); }; const fromPromise = (promise: Promise): FutureResult => { return nu((completer: (result: Result) => void) => { promise.then((value) => { completer(Result.value(value)); }, (error: E) => { completer(Result.error(error)); }); }); }; export const FutureResult = { nu, wrap, pure: value, value, error, fromResult, fromFuture, fromPromise };