import { CallbackFunction } from './callback-function' ; import { MaybeEmptyError } from './maybe-empty-error' ; export class Maybe < T > { private constructor ( private value ) { } static none < T > ( ) { return new Maybe < T > ( null ) ; } static from < T > ( value ) { return this . isValid ( value ) ? Maybe . some ( value as T ) : Maybe . none < T > ( ) ; } private static some < T > ( value ) { if ( ! this . isValid ( value ) ) { throw new MaybeEmptyError ( ) ; } return new Maybe ( value ) ; } private static isValid ( value ) { return ! ( value === undefined || value === null || this . isEmptyMaybe ( value ) ) ; } private static isEmptyMaybe < R > ( value ) { if ( this . isMaybe ( value ) ) { return ! value . has ( ) ; } return false ; } private static isMaybe ( value ) { return value instanceof Maybe ; } has ( ) { return this . value !== null ; } getOrElse ( defaultValue ) { return this . value === null ? defaultValue : this . value ; } getOrOther < R = T > ( defaultValue ) { return this . value === null ? defaultValue : this . value ; } getOrExecute ( defaultValue ) { return this . value === null ? defaultValue ( ) : this . value ; } map < R > ( f ) { if ( this . value === null ) { return Maybe . none < R > ( ) ; } else { return Maybe . some ( f ( this . value ) ) ; } } tap ( f ) { if ( this . value !== null ) { f ( this . value ) ; } return Maybe . from ( this . value ) ; } flatMap < R > ( f ) { if ( this . value === null ) { return Maybe . none < R > ( ) ; } else { return f ( this . value ) ; } } getOrThrow ( error ? ) { return this . value === null ? ( ( ) => { if ( error !== undefined ) { throw error ; } throw new MaybeEmptyError ( ) ; } ) ( ) : this . value ; } orElse ( value ) { return this . value === null ? value : this ; } }