import {Func, optional, predication, consumer, supplier} from "../Interface"; import {Predication} from "./Predication"; import {Objects} from "../type/Objects"; import {Consumer} from "../Consumer"; /**** * @class Optional * @interface optional */ export class Optional implements optional{ /** */ private static readonly EMPTY = new Optional(void 0); protected value : T; constructor( value : T ) {this.value = value;} /*** * @isPresent */ public isPresent( ){return this.value!==null&&this.value!==undefined;} /*** * @ifPresent */ public ifPresent(consumer:consumer):void{ if( typeof consumer === "function") consumer = Consumer.of(consumer); if(this.isPresent()) consumer.accept(this.value); } /*** * @isEmpty */ public isEmpty( ){return !this.isPresent();} /*** * @equals */ public equals( obj : Object ): boolean {return this.value===obj;} /*** * @get */ public get(): T { return this.value; } /*** * @map */ public map( callback:Func ): Optional { return Optional.ofNullable(callback.call(null, this.value )); } /*** * @deprecated * @alternatives map * @param callback */ //public mapTo( callback:Func ): Optional {return this.map(callback);} /*** * @filter */ public filter( predicate: predication ): Optional { if( !(predicate instanceof Predication) ) predicate = Predication.of(predicate); if(this.isEmpty()) return this; return new Optional(predicate.test(this.value) ?this.value:null ); } /*** * @orElse */ public orElse(other: T): T {return !this.isEmpty() ? this.value:other;} /*** * @orElseThrow */ public orElseThrow( other : U ): T { if(!this.isEmpty()) return this.value; throw other; } /*** * @orElseGet */ public orElseGet(other: supplier ):T{ if(!this.isEmpty()) return this.value; else { return other.get(); } } /*** * @orElseGet */ public orElseThrowSupplier(supplier :supplier){ if(!this.isEmpty()) return this.value; else{ throw supplier.get(); } } /*** * @of */ public static of( value : T ) : Optional{ return new Optional(Objects.requireNotNull(value,"Optional value is null use ofNullable method")); } /*** * @ofNullable */ public static ofNullable( value : T ): Optional{return new Optional( value );} /*** * @empty */ public static empty():Optional{return Optional.EMPTY;} /*** * @valueOf */ public valueOf( ):Object{return this.value; } /***/ public toString( ):string{ return this.isPresent() ? `Optional[${this.value}]` : "Optional.empty"; } } Object.package(this);