All files OneOf.ts

100% Statements 14/14
100% Branches 6/6
100% Functions 4/4
100% Lines 13/13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29    1x   1x       1x 1x     1x 3x   3x 1x     2x 4x 1x     3x     1x  
import { NonEmptyArray } from 'fp-ts/lib/NonEmptyArray';
 
import Decoder, { Decoded } from './Decoder';
 
export default class OneOf<a> extends Decoder<a> {
  private decoders: NonEmptyArray<Decoder<a>>;
 
  constructor(decoders: NonEmptyArray<Decoder<a>>) {
    super();
    this.decoders = decoders;
  }
 
  public run(value: unknown): Decoded<a> {
    const firstResult = this.decoders.head.run(value);
 
    if (firstResult.isSuccess()) {
      return firstResult;
    }
 
    return this.decoders.tail.reduce((decoded: Decoded<a>, decoder: Decoder<a>) => {
      if (decoded.isSuccess()) {
        return decoded;
      }
 
      return decoder.run(value);
    }, firstResult);
  }
}