【问题标题】:Compositional function that executes each function until "truthy" value is returned执行每个函数直到返回“真实”值的组合函数
【发布时间】:2019-09-06 17:57:56
【问题描述】:

我正在寻找一种在 lodash 中将类似于 overSomeflow 的函数链接在一起的方法。

这是写出的类似函数。

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 的组合函数库?

【问题讨论】:

  • 我认为这是 Maybe/Option monad 的完美用例。我建议查看fp-tspurify-ts 或类似的。对于fp-ts,您可能需要使用Optionpipechain,如果混合使用异步,则使用Task

标签: typescript lodash fp-ts


【解决方案1】:

您可以使用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();

如果你喜欢从左到右的构图,你可以使用pipeWith

工作示例:https://repl.it/repls/TemptingAridGlitch

【讨论】:

  • 我无法让这个例子的打字正常工作。我也在寻找一个行为类似于_.flow 的简单函数,我可以在其中获得正确类型的返回函数。
猜你喜欢
  • 1970-01-01
  • 2012-11-29
  • 2014-02-17
  • 1970-01-01
  • 1970-01-01
  • 2015-12-17
  • 1970-01-01
  • 2020-03-11
  • 1970-01-01
相关资源
最近更新 更多