Skip to content

Commit 2877e99

Browse files
author
Elias Mulhall
committed
Add Result.errors utility
Counterpart to Result.successes
1 parent b111a59 commit 2877e99

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

src/result.ts

+6
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,12 @@ export const withException = <V>(r: Result<V, any>): V => {
9999
export const successes = <A>(results: Result<A, any>[]): A[] =>
100100
results.reduce((acc: A[], r: Result<A, any>) => (r.ok === true ? acc.concat(r.result) : acc), []);
101101

102+
/**
103+
* Given an array of `Result`s, return the error values.
104+
*/
105+
export const errors = <E>(results: Result<any, E>[]): E[] =>
106+
results.reduce((acc: E[], r: Result<any, E>) => (r.ok === false ? acc.concat(r.error) : acc), []);
107+
102108
/**
103109
* Apply `f` to the result of an `Ok`, or pass the error through.
104110
*/

test/json-decode.test.ts

+9-4
Original file line numberDiff line numberDiff line change
@@ -1059,11 +1059,16 @@ describe('Result', () => {
10591059
});
10601060
});
10611061

1062-
it('can return successes from an array of decoded values', () => {
1062+
describe('can filter and unwrap arrays of Results', () => {
10631063
const json: unknown = [1, true, 2, 3, 'five', 4, []];
1064-
const jsonArray: unknown[] = Result.withDefault([], array().run(json));
1065-
const numbers: number[] = Result.successes(jsonArray.map(number().run));
1064+
const numberResults = Result.withDefault([], array(result(number())).run(json));
10661065

1067-
expect(numbers).toEqual([1, 2, 3, 4]);
1066+
it('can return successes from an array of decoded values', () => {
1067+
expect(Result.successes(numberResults)).toEqual([1, 2, 3, 4]);
1068+
});
1069+
1070+
it('can return failures from an array of decoded values', () => {
1071+
expect(Result.errors(numberResults).map(({input}) => input)).toEqual([true, 'five', []]);
1072+
});
10681073
});
10691074
});

0 commit comments

Comments
 (0)