import { Effect , Dispatch } from "./index" ; export function none < Action > ( ) { return [ ] ; } export function delay < Action > ( action , delay ) { return [ dispatch => setTimeout ( ( ) => dispatch ( action ) , delay ) ] ; } export function action < Action > ( action ) { return [ dispatch => dispatch ( action ) ] ; } export function fromPromise < Action , Value = unknown , Err = Error > ( promise , ofSuccess , ofError ) { return effectFromPromise < Action , Value , Err > ( promise , ofSuccess , ofError ) ; } export function dispatchFromPromise < Action , Err = Error > ( promise , ofError ) { return effectFromPromise < Action , Action , Err > ( promise , ( x ) => x , ofError ) ; } export function attemptPromise < Action , Value = unknown , Err = Error > ( promise , ofError ) { return effectFromPromise < Action , Value , Err > ( promise , ofError ) ; } function effectFromPromise < Action , Value , Err > ( promise , ofSuccess , ofError ? ) { const handleError = ofError === undefined ? ofSuccess as ( ( error : Err ) => Action ) : ofError ; const handleSuccess = ofError === undefined ? undefined : ofSuccess as ( ( value : Value ) => Action ) ; return [ ( dispatch ) => ( promise ( ) . then ( value => { if ( handleSuccess !== undefined ) { dispatch ( handleSuccess ( value ) ) ; } } ) . catch ( error => { dispatch ( handleError ( error ) ) ; } ) ) ] ; } export function dispatchFromFunction < Action , Err = Error > ( f , ofError ) { return effectFromFunction < Action , Action , Err > ( f , ( x ) => x , ofError ) ; } export function fromFunction < Action , Value = unknown , Err = Error > ( f , ofSuccess , ofError ) { return effectFromFunction < Action , Value , Err > ( f , ofSuccess , ofError ) ; } export function attemptFunction < Action , Value = unknown , Err = Error > ( f , ofError ) { return effectFromFunction < Action , Value , Err > ( f , ofError ) ; } function effectFromFunction < Action , Value , Err > ( f , ofSuccess , ofError ? ) { const handleError = ofError === undefined ? ofSuccess as ( ( error : Err ) => Action ) : ofError ; const handleSuccess = ofError === undefined ? undefined : ofSuccess as ( ( value : Value ) => Action ) ; return [ ( dispatch ) => { try { const value = f ( ) ; if ( handleSuccess !== undefined ) { dispatch ( handleSuccess ( value ) ) ; } } catch ( error ) { dispatch ( handleError ( error ) ) ; } } ] ; } export function fromIterator < Action > ( iterator ) { return [ dispatch => { for ( const action of iterator ) { dispatch ( action ) ; } } ] ; } export function combine < Action > ( ... effects ) { return effects . reduce ( ( prev , effect ) => [ ... prev , ... effect ] , [ ] ) ; }