Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Created February 9, 2023 21:32
Show Gist options
  • Save JamieMason/50f1d47127ce181c55f9a21bff9c1a22 to your computer and use it in GitHub Desktop.
Save JamieMason/50f1d47127ce181c55f9a21bff9c1a22 to your computer and use it in GitHub Desktop.
Additional helpers for https://mobily.github.io/ts-belt/api/result. R.all, R.onlyOk
import { R } from '@mobily/ts-belt';
/** Additional helpers for https://mobily.github.io/ts-belt/api/result */
export const $R = {
/**
* 1. Return an R.Ok<output[]> if every R.Result succeeds
* 2. Return an R.Error<Error> for the first failure encountered
*/
all<Input, Output = Input>(
getResult: (value: Input) => R.Result<Output, Error>,
) {
return (inputs: Input[]): R.Result<Output[], Error> => {
const outputs: Output[] = [];
for (const value of inputs) {
const result = getResult(value);
if (R.isError(result)) return result;
outputs.push(R.getExn(result));
}
return R.Ok<Output[]>(outputs) as R.Result<Output[], Error>;
};
},
/**
* 1. Return an R.Ok<output[]> of every R.Result which succeeded
* 2. Return an R.Error<Error> if none succeeded
*/
onlyOk<Input, Output = Input>(
getResult: (value: Input) => R.Result<Output, Error>,
) {
return (inputs: Input[]): R.Result<Output[], Error> => {
const outputs: Output[] = [];
for (const value of inputs) {
const result = getResult(value);
if (R.isError(result)) continue;
outputs.push(R.getExn(result));
}
return outputs.length > 0
? (R.Ok<Output[]>(outputs) as R.Result<Output[], Error>)
: R.Error(new Error('No R.Ok() returned by $R.onlyOk'));
};
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment