All files Array.ts

100% Statements 23/23
100% Branches 4/4
100% Functions 10/10
100% Lines 19/19
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 30 31 32 33 34 35 36 371x 1x   1x   1x       10x 10x     10x 10x 5x 6x   6x   3x   3x 1x 2x     3x         5x 5x   1x  
import { nonEmptyArray } from 'fp-ts/lib/NonEmptyArray';
import * as ValidationFn from 'fp-ts/lib/Validation';
 
import Decoder, { Decoded } from './Decoder';
 
export default class ArrayD<a> extends Decoder<a[]> {
  private decoder: Decoder<a>;
 
  constructor(decoder: Decoder<a>) {
    super();
    this.decoder = decoder;
  }
 
  public run(valueArray: unknown): Decoded<a[]> {
    if (Array.isArray(valueArray)) {
      return valueArray.reduce((validated: Decoded<a[]>, nextValue: unknown, index: number): Decoded<a[]> => {
        const validatedValue = this.decoder.run(nextValue);
 
        return validatedValue.fold(
          (errorsFromValue) => {
            const errors = errorsFromValue.map((errorText) => `${errorText} at index #${index}`);
 
            return validated.fold(
              (errorsFromValidated) => ValidationFn.failure(errorsFromValidated.concat(errors)),
              () => ValidationFn.failure(errors),
            );
          },
          (successFromValue) => validated.map((successes) => [...successes, successFromValue]),
        );
      }, ValidationFn.success([]));
    }
 
    const message = `Value must be an array, found "${typeof valueArray}" instead`;
    return ValidationFn.failure(nonEmptyArray.of(message));
  }
}