/**
 * Copyright (c) 2016-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */ import * as List from './list' ; interface SharedState < T > { value ? : T ; thenHandlers : { ( val ) : void ; } [ ] ; } export function pending < T > ( ) { return new Promise < T > ( { value : undefined , thenHandlers : [ ] } ) ; } export function resolved < T > ( val ) { return new Promise < T > ( { value : val , thenHandlers : [ ] } ) ; } export class Promise < T > { private sharedState : SharedState < T > ; constructor ( sharedState ) { this . sharedState = sharedState ; } getFuture ( ) { return new Future < T > ( this . sharedState ) ; } setValue ( val ) { this . sharedState . value = val ; this . sharedState . thenHandlers . forEach ( function ( f ) { f ( val ) ; } ) ; } } export class Future < T > { /**
      The state that is shared between the future and the promise. You would
      really like this ot be "friend" for the exported functions but there is
      no way to do this inside of typescript. Nobody should touch it, hence the
      `_` indicating that this should be treated as an implementation detail.
    */ public _sharedState : SharedState < T > ; /**
      A Future<T> should never be allocated apart from reading one from a promise
      using getFuture or a combinator from another future. Ideally this
      constructor could be marked private for the module but typescript does not
      allow for that.
    */ constructor ( sharedState ) { this . _sharedState = sharedState ; } map < U > ( f ) { return map ( f , this ) ; } } export function then < T > ( f , future ) { if ( future . _sharedState . value === undefined ) { future . _sharedState . thenHandlers . push ( f ) ; } else { f ( future . _sharedState . value ) ; } } export function map < T , U > ( f , future ) { const pendingPromise = pending < U > ( ) ; then ( function ( val ) { pendingPromise . setValue ( f ( val ) ) ; } , future ) ; return pendingPromise . getFuture ( ) ; } export function mbind < T , U > ( f , future ) { const pendingPromise = pending < U > ( ) ; then ( function ( val ) { then ( function ( val2 ) { pendingPromise . setValue ( val2 ) ; } , f ( val ) ) ; } , future ) ; return pendingPromise . getFuture ( ) ; } export function munit < T > ( t ) { return resolved ( t ) . getFuture ( ) ; } export function aapply < T , U > ( futureFunc , futureVal ) { return mbind ( function ( t ) { return map ( function ( f ) { return f ( t ) ; } , futureFunc ) ; } , futureVal ) ; } export function all < T > ( futures ) { const partialFutures = List . map ( function ( future ) { return map ( function ( val ) { return ( result ) => List . cons ( val , result ) ; } , future ) ; } , futures ) ; return List . foldr ( function ( soFarFuture , thisFuture ) { return aapply ( thisFuture , soFarFuture ) ; } , resolved < List . List < T > > ( List . of < T > ( ) ) . getFuture ( ) , partialFutures ) ; }