UNPKG

@typed/io

Version:

Runtime IO type system

25 lines 1.21 kB
import { combine } from '@typed/effects'; import { fromLeft, fromRight, isLeft, isRight } from '@typed/either'; import { Just } from '@typed/maybe'; import { toString } from '@typed/strings'; import * as G from '../guard'; import { catchDecodeFailure, DecodeError, decodeFailure, Decoder, } from './Decoder'; import { refinement } from './refinement'; export const Array = Decoder.fromGuard(G.Array, 'ReadonlyArray<unknown>'); export const array = (decoder) => refinement(Array, function* (input) { if (input.length === 0) { return input; } const decoded = yield* combine(...input.map((i, index) => catchDecodeFailure(decoder.decode(i), () => index))); if (decoded.every(isRight)) { return decoded.map((d) => fromRight(d)); } const errors = decoded.filter(isLeft).map(fromLeft); return yield* decodeFailure(formatArrayErrors(errors, toString(input), decoder.expected)); }, `ReadonlyArray<${decoder.expected}>`); function formatArrayErrors(errors, value, expected) { return DecodeError.create(`ReadonlyArray<${expected}>`, value, { errors: errors.map(([e, key]) => ({ ...e, key: Just.of(key.toString()) })), }); } //# sourceMappingURL=Array.js.map