Created
March 28, 2021 14:19
-
-
Save uladkasach/9b5e7f79386f20bed2c763059f5ae6cb to your computer and use it in GitHub Desktop.
withCastingOutput
This file contains hidden or 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 { 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"); | |
}); | |
}); |
This file contains hidden or 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
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