Skip to content

Commit

Permalink
fix(array): array decoder short circuiits on failure
Browse files Browse the repository at this point in the history
  • Loading branch information
kofno committed Jun 26, 2019
1 parent 051996c commit f34b777
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions src/Decoder.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { just, Maybe, nothing } from 'maybeasy';
import { err, ok, Result } from 'resulty';
import { err, Err, ok, Result } from 'resulty';
import { stringify } from './Internal/ErrorStringify';

/**
Expand Down Expand Up @@ -214,14 +214,19 @@ export const array = <A>(decoder: Decoder<A>): Decoder<A[]> =>
return err(errorMsg) as Result<string, A[]>;
}

return value.reduce((memo: Result<string, A[]>, element, idx) => {
return memo.andThen(results => {
return decoder
.decodeAny(element)
.mapError(s => `I found an error in the array at [${idx}]: ${s}`)
.map(v => results.concat([v]));
});
}, ok([]));
let result: Result<string, A[]> = ok([]);

for (let idx = 0; idx < value.length; idx++) {
result = decoder
.decodeAny(value[idx])
.andThen(v => result.map(vs => vs.concat([v])))
.mapError(e => `I found an error in the array at [${idx}]: ${e}`);
if (result instanceof Err) {
break;
}
}

return result;
});

/**
Expand Down

0 comments on commit f34b777

Please sign in to comment.