我正在学习 pointfree 函数,并尝试以这种方式实现这种递归 null 删除器。
有效,但不无意义:
function removeNulls(obj) {
return R.ifElse(
R.either(R.is(Array), R.is(Object)),
R.pipe(
R.filter(R.pipe(R.isNil, R.not)),
R.map(removeNulls)
),
R.identity
)(obj)
}
module.exports = removeNulls
以下是我的无效尝试:
const removeNulls = R.ifElse(
R.either(R.is(Array), R.is(Object)),
R.pipe(
R.filter(R.pipe(R.isNil, R.not)),
// throws `ReferenceError: removeNulls is not defined`
R.map(removeNulls)
),
R.identity
)
最佳答案
幸运的是,JavaScript 有资源来处理它缺乏惰性的问题。因此,完全可以通过以下方式使用 lambda 函数来声明递归无点解决方案:a => f(a)
。只需将 R.map(removeNull)
替换为 R.map(a => removeNull(a))
。
const removeNulls = R.ifElse(
R.either(R.is(Array), R.is(Object)),
R.pipe(
R.filter(R.pipe(R.isNil, R.not)),
R.map(a => removeNulls(a))
),
R.identity
)
在您的情况下,我建议您使用 R.reject
,它与 R.filter
相反。由于您要否定谓词,R.filter(R.pipe(R.isNil, R.not))
等于 R.reject(R.isNil)
const removeNulls = R.ifElse(
R.either(R.is(Array), R.is(Object)),
R.pipe(
R.reject(R.isNil),
R.map(a => removeNulls(a))
),
R.identity
)
最后,此函数具有以下结构 ifElse(predicate, whenTrue, identity)
等于 when(predicate, whenTrue)
const removeNulls = R.when(
R.either(R.is(Array), R.is(Object)),
R.pipe(
R.reject(R.isNil),
R.map(a => removeNulls(a))
)
)
简化版本,关于 Declan Whelan 的评论,因为数组是对象
const removeNulls = R.when(
R.is(Object),
R.pipe(
R.reject(R.isNil),
R.map(a => removeNulls(a))
)
)
关于javascript - 如何使用无点递归实现使用 Ramda 删除对象中的空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40985044/