diff --git a/src/Helpers/async-pipe.test.ts b/src/Helpers/async-pipe.test.ts new file mode 100644 index 00000000..6e008d19 --- /dev/null +++ b/src/Helpers/async-pipe.test.ts @@ -0,0 +1,34 @@ +import { identity } from 'ramda' +import { describe } from 'riteway' +import { asyncPipe } from './async-pipe' +import { toPromise } from './to-promise' + +const double = (x: number) => x * 2 +const inc = (x: number) => x + 1 + +const doubleP = toPromise(double) +const incP = toPromise(inc) + +describe('asyncPipe', async (assert: any) => { + const should = 'apply the value to the functions composition correctly' + + { + const value = 10 + assert({ + given: 'sync and async functions', + should, + actual: await asyncPipe(doubleP, inc)(value).catch(identity), + expected: inc(await doubleP(value)), + }) + } + + { + const value = 10 + assert({ + given: 'nested compositions of sync and async functions', + should, + actual: await asyncPipe(doubleP, inc, asyncPipe(double, incP))(value).catch(identity), + expected: await incP(double(inc(await doubleP(value)))), + }) + } +}) diff --git a/src/Helpers/async-pipe.ts b/src/Helpers/async-pipe.ts new file mode 100644 index 00000000..f57c90d9 --- /dev/null +++ b/src/Helpers/async-pipe.ts @@ -0,0 +1,4 @@ +type Func = (v?: any) => any | Promise + +type asyncPipe = (...fns: Func[]) => (v?: any) => Promise +export const asyncPipe: asyncPipe = (...fns) => v => fns.reduce(async (a, c) => c(await a), v) diff --git a/tests/unit/index.ts b/tests/unit/index.ts index bc41007f..34a3a702 100644 --- a/tests/unit/index.ts +++ b/tests/unit/index.ts @@ -14,6 +14,7 @@ import '../../src/Helpers/Configuration.test' import '../../src/Helpers/FetchError.test.ts' import '../../src/Helpers/Logging.test.ts' import '../../src/Helpers/Time.test.ts' +import '../../src/Helpers/async-pipe.test.ts' import '../../src/Helpers/camelCaseToScreamingSnakeCase.test' import '../../src/Helpers/isTruthy.test' import '../../src/Helpers/to-promise.test.ts'