与Ramda一起使用JavaScript和Typescript中的函数式编程,我经常发现自己正在编写类似以下代码:
const myFun = c => {
const myId = c.id
const value = pipe(
getAnotherOtherPropOfC,
transformToArray,
mapToSomething,
filterSomething,
// ... N other transformations
// ok now I need myId and also the result of the previous function
chainMyIdWithResultOfPreviousFunction(myId)
)(c)
return value
}
注意创建const myId
如何破坏无点样式。我想写myFun
,所以不需要显式的c
。所以像这样:const myFun = pipe(....)
我想知道是否有一种更实用,更易读的方式来做这样的事情。
变量通常表示您的函数执行过多操作,应将其分解。例如,此
const myFun = c => {
let id = c.id;
return R.pipe(
R.prop('list'),
R.map(R.add(10)),
R.sum,
R.subtract(id),
)(c)
}
可以重构为两个独立的函数:
const compute = R.pipe(
R.prop('list'),
R.map(R.add(10)),
R.sum,
);
const getId = R.prop('id');
然后简单地
const myFun = c => getId(c) - compute(c)
这对我来说看起来足够好,但是如果您想绝对没有问题,那么
const myFun = R.converge(R.subtract, [getId, compute])