import Exceptional from "./Exceptional"; export default class EtudeParser { private objects: Object[]; private constructor(private t: T, private exception: Error) { this.objects = []; } private isInvalid(): boolean { return this.exception != null; } public static of(t: T, exception: Error = null): EtudeParser { return new EtudeParser(t, exception); } public map(func: (T) => S): EtudeParser { return this.isInvalid() ? EtudeParser.of(null, this.exception) : EtudeParser.of(func(this.t)); } public filter(predicate: (T) => boolean, exception: Error): EtudeParser { return this.isInvalid() ? this : (predicate(this.t) ? this : EtudeParser.of(this.t, exception) ); } public parse(func: (T) => Exceptional): EtudeParser { if (this.isInvalid()) { return this; } const exceptional: Exceptional = func(this.t); if (!exceptional.isPresent()) { return EtudeParser.of(this.t, exceptional.getException()); } this.objects.push(exceptional.get()); return this; } public get(func: (o: Object[]) => T): Exceptional { return this.isInvalid() ? Exceptional.empty(this.exception) : Exceptional.of(func(this.objects)); } }