是否可以将以下函数的内部写为一行?我想要一种不必声明check
的方法。
function Example {
const check = this.readByUuidCheck(props)
if (check) return this.readByUuid(check)
}
我正在寻找一种减少重复的方法:
function Example {
const check = this.readByUuidCheck(props)
if (check) return this.readByUuid(check)
const alpha = this.alphaCheck(props)
if (alpha) return this.alpha(alpha)
const beta = this.betaCheck(props)
if (beta) return this.beta(beta)
const gamma = this.gammaCheck(props)
if (gamma) return this.gamma(gamma)
}
我接受了这种抽象:
function manage <T extends (...args: any) => any>(checker, method: T): (props:any) => ReturnType<T> {
return (props: any) => {
const check = checker(props)
if (check) return method(check)
throw new Error('Unable to run')
}
}
function resolve(props:
Props<ContactService['readById']> |
Props<ContactService['readByUuid']> |
Props<ContactService['readByUser']> |
Props<ContactService['lookupOrUpsert']> |
Props<ContactService['upsertOwnedByUser']> |
Props<ContactService['handleCreateMemberArgs']> |
Props<ContactService['handleCreateMemberArgsAlt']>
): Promise<[Contact, 'read' | 'create' | 'update' | null]> {
return helper.compose.first(
manage(this.readByIdCheck, this.readById),
manage(this.readByUuidCheck, this.readByUuid),
manage(this.readByUserCheck, this.readByUser),
manage(this.lookupOrUpsertCheck, this.lookupOrUpsert),
manage(this.upsertOwnedByUserCheck, this.upsertOwnedByUser),
manage(this.handleCreateMemberArgsCheck, this.handleCreateMemberArgs),
manage(this.handleCreateMemberArgsAltCheck, this.handleCreateMemberArgsAlt),
helper.compose.error(new Error('unable to resolve contact'))
)()
}