import { isObservableArray , IObservableArray } from 'mobx' ; import { Validator , ValidationResponse , ValidatorResponse } from './types' ; export function isPromiseLike ( arg ) { return arg != null && typeof arg === 'object' && typeof arg . then === 'function' ; } export function isEmpty ( response ) { return ! response ; } export function asyncResponsesAnd ( asyncResponses ) { if ( asyncResponses . length === 0 ) { return null ; } return new Promise ( resolve => { asyncResponses . forEach ( asyncResponse => asyncResponse . then ( Response => { if ( ! isEmpty ( Response ) ) { resolve ( Response ) ; } } ) ) ; return Promise . all ( asyncResponses ) . then ( responses => { if ( responses . every ( isEmpty ) ) { resolve ( null ) ; } } ) ; } ) ; } export function applyValidators < TValue > ( value , validators ) { if ( validators . length === 0 ) { return null ; } if ( validators . length === 1 ) { return validators [ 0 ] ( value ) ; } const asyncResponses = [ ] ; for ( const validator of validators ) { const response = validator ( value ) ; if ( isPromiseLike ( response ) ) { asyncResponses . push ( response ) ; continue ; } if ( ! isEmpty ( response ) ) { return response ; } } return asyncResponsesAnd ( asyncResponses ) ; } export function debounce ( fn , delay ) { let timeout = null ; return ( ) => { if ( timeout ) { clearTimeout ( timeout ) ; } timeout = setTimeout ( fn , delay ) ; } ; } export function isArrayLike ( value ) { return Array . isArray ( value ) || isObservableArray ( value ) ; }