【问题标题】:nested placeholders in RamdaRamda 中的嵌套占位符
【发布时间】:2017-08-09 23:27:44
【问题描述】:

我正在尝试将一个函数传递给一个过滤器,该过滤器本身嵌套在更深的函数中

从概念上讲,类似这样的(损坏的)示例:

const testData = [
  {foo: "foo", bar: ""}
];

const myFilter = a => !R.isEmpty(a);

const clean = R.when(
    R.either(R.is(Array), R.is(Object)),
    R.pipe(
        R.map(a => clean(R.__)(a)),
        R.filter(R.__)
    )
)

const cleanEmpties = clean(myFilter);

cleanEmpties(testData); //fail: should not include `bar`, but it does

这样做的正确方法是什么?

为了说明这一点,这个硬编码的替代方案确实可以按预期工作:

const cleanEmpties = R.when(
    R.either(R.is(Array), R.is(Object)),
    R.pipe(
        R.map(a => cleanEmpties(a)),
        R.filter(myFilter)
    )
)

cleanEmpties(testData); //working, does not include `bar`

【问题讨论】:

    标签: javascript ramda.js


    【解决方案1】:

    问题在于R.__ 在同一函数中被多次引用时如何解释。如果您没有传入足够的参数,则会返回一个柯里化函数,该函数期望更多的参数来填补空白。

    R.gt(4,3) // true
    R.gt(R.__, R.__)(4, 3) //true
    R.gt(R.__, R.__)(4)(3) //true
    R.gt(R.__, R.__)(4) // function n(r){return 0===arguments.length||b(r)?n:t.apply(this,arguments)}
    

    如果您更改函数语法以接受显式 arg,则代码将按预期工作:

    const clean = f => R.when(
      R.either(R.is(Array), R.is(Object)),
      R.pipe(
        R.map(a => clean(f)(a)),
        R.filter(f)
      )
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      • 2022-11-23
      • 2016-01-16
      相关资源
      最近更新 更多