Typescript 合成函数,执行每个函数直到;“真实的”;返回值
我正在寻找一种将函数链接在一起的方法,类似于lodash中的Typescript 合成函数,执行每个函数直到;“真实的”;返回值,typescript,lodash,fp-ts,Typescript,Lodash,Fp Ts,我正在寻找一种将函数链接在一起的方法,类似于lodash中的overSome或flow 这是写出的可比函数 const e = async ({planGroups, uuid, name, user, organization}) => { const a = this.getPlanGroupByUuid({ planGroups, uuid }) if (a) return a const b = this.getPlanGroupByName({ planGroups,
overSome
或flow
这是写出的可比函数
const e = async ({planGroups, uuid, name, user, organization}) => {
const a = this.getPlanGroupByUuid({ planGroups, uuid })
if (a) return a
const b = this.getPlanGroupByName({ planGroups, name })
if (b) return b
const c = await this.createPlanGroup({ name, user, organization })
return c
}
e({planGroups, uuid, name, user, organization})
这将是合成版本
const x = await _.overSome(this.getPlanGroupByUuid, this.getPlanGroupByName, this.createPlanGroup)
x({planGroups, uuid, name, user, organization})
其思想是该函数返回第一个带有truthy
值的函数
仅在lodash中就可能实现这一点吗?是否有更好的支持typescript的合成函数库?您可以使用
ramda
来实现这一点。例如:
const composeWhileNotNil = R.composeWith(async (f, res) => {
const value = await res;
return R.isNil(value) ? value : f(value)
});
const getA = x => x * 2
const getB = x => Promise.resolve(x * 3)
const getC = x => x * 10
async function run(){
const result = await composeWhileNotNil([getC, getB, getA])(1);
console.log("result:", result); // result: 60
}
run();
如果你喜欢左到右构图,你可以使用
工作示例:我认为这是可能/选项单子的完美用例。我建议您查看
fp-ts
,purify-ts
,或类似内容。在fp ts
的情况下,您可能需要使用选项
,管道
,链
,如果混合中存在异步,则任务
。对于本例,我无法使键入正常工作。我也在寻找一个行为类似于.flow
的简单函数,在这里我可以得到一个正确类型的返回函数。