Skip to content

Instantly share code, notes, and snippets.

@Grubba27
Last active February 22, 2023 02:07
Show Gist options
  • Select an option

  • Save Grubba27/4dd728e1c3c823e44968ce921543b4db to your computer and use it in GitHub Desktop.

Select an option

Save Grubba27/4dd728e1c3c823e44968ce921543b4db to your computer and use it in GitHub Desktop.
try implementing
type Creator =
<Name extends string, Args, Response>
(name: Name, runner: (args: Args) => Response, subModule?: RCreator<Name, Args, Response>) =>
RCreator<Name, Args, Response>
const createModule: Creator = (name, runner, subModule) => {
return {
...subModule,
[name]: runner
}
}
const k = createModule('foo', (s: string) => 1)
const t = {...k}
type RCreator<Name extends string, Args, Response> = { [P in Name]: (args: Args) => Response }
const factory =
<Name extends string, Args, Response>
(subModules?: RCreator<Name, Args, Response>) => {
const addMethod =
<Name extends string, Args, Response>
(name: Name, runner: (args: Args) => Response) => {
const op: RCreator<Name, Args, Response> = createModule(name, runner)
const module: RCreator<Name, Args, Response> = {
...op,
...subModules,
}
return factory(module as RCreator<Name, Args, Response> )
}
const addQuery = addMethod
const addMutation = addMethod
const toRunner = () => {
if (!subModules) {
throw new Error('No modules added')
}
return subModules
}
return {
addMethod,
addQuery,
addMutation,
toRunner
}
}
const M =
factory()
.addMethod('sum', ({a, b}: { a: number, b: number }) => a + b)
.addMethod('sub', ({a, b}: { a: number, b: number }) => a - b)
.addMutation('mul', ({a, b}: { a: number, b: number }) => a * b)
.toRunner()
const r = M.mul({a: 1, b: 2})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment