Created
February 9, 2023 21:32
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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