Skip to content

Instantly share code, notes, and snippets.

@uladkasach
Created March 28, 2021 14:19
Show Gist options
  • Save uladkasach/9b5e7f79386f20bed2c763059f5ae6cb to your computer and use it in GitHub Desktop.
Save uladkasach/9b5e7f79386f20bed2c763059f5ae6cb to your computer and use it in GitHub Desktop.
withCastingOutput
import { withCastingOutput } from './withCastingOutput';
describe('withCastingOutput', () => {
it('should be able to wrap a function and add output casting to it', async () => {
const startFromTheBottom = ({ bottom }: { bottom: boolean }) => ({
started: `started from the ${bottom ? 'bottom' : 'top'}`,
bottom,
});
const castToHere = ({ started, bottom }: { started: string; bottom?: boolean }) =>
`${started}${bottom ? ", now we're here" : " and we're still here"}`;
const startAndGetHere = withCastingOutput(startFromTheBottom, castToHere);
expect(await startAndGetHere({ bottom: true })).toEqual("started from the bottom, now we're here");
expect(await startAndGetHere({ bottom: false })).toEqual("started from the top and we're still here");
});
});
export const withCastingOutput = <
Input extends Parameters<Logic>[0],
OutputIn extends ReturnType<Logic>,
Logic extends (input: any) => any,
OutputOut extends ReturnType<Cast>,
Cast extends (input: OutputIn) => any
>(
logic: Logic,
cast: Cast,
) => {
return async (input: Input): Promise<OutputOut> => {
const outputIn = await logic(input);
const outputOut = await cast(outputIn);
return outputOut;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment