import { isNullOrUndefined } from './Core'; import { Stream } from './stream'; export class Optional { public static of(value: U | undefined): Optional { return new Optional(value); } public readonly value: T | undefined; private constructor(value?: T) { this.value = value; } public filter(predicate: (t: T) => boolean): Optional { return this.isPresent() && predicate(this.value as T) ? this : new Optional(); } public ifPresent(consumer: (t: T) => void): void { if (this.isPresent()) { consumer(this.value as T); } } public ifPresentOrElse(consumer: (t: T) => void, otherwise?: () => void): void { if (this.isPresent()) { consumer(this.value as T); } else { if (otherwise != null || otherwise !== undefined) { otherwise(); } else { throw new Error('Otherwise mustnot be undefined or null!'); } } } public isPresent(): boolean { return isNullOrUndefined(this.value); } public map(func: (t: T) => U): Optional { if (this.isPresent()) { return Optional.of(func(this.value as T)); } else { throw new Error('IllegalOperation for empty tsava.util.Optional instance!'); } } public or(supplier: () => T): Optional { return this.isPresent() ? this : Optional.of(supplier()); } public orElse(value: T): Optional { return this.isPresent() ? this : Optional.of(value); } public orElseGet(supplier: () => T): Optional { return this.isPresent() ? this : Optional.of(supplier()); } public orElseThrow(supplier: () => E): Optional { if (this.isPresent()) { return this; } else { throw supplier(); } } public toString(): string { return 'tsava.util.Optional[' + (!isNullOrUndefined(this.value) ? 'value=' + (this.value as T).toString() : '') + ']'; } }