了解 Ramda 中转换器的使用

Understanding the use of transducers in Ramda

给定以下代码:

const objs = [
  {
    name: '1st',
    completed: false,
  },
  {
    name: '2nd',
    completed: true,
  },
  {
    name: '3rd',
    completed: true,
  },
]

const transducer = R.pipe(
  R.filter(R.propEq('completed', true)),
  R.map((obj) => {
    return {
      label: `${obj.name} (${obj.completed.toString()})`,
    }
  }),
)

const intoArray = R.into([])

console.log('-- working --')
console.log(transducer(objs))

console.log('-- not working --')
console.log(intoArray(transducer, objs))

当使用 R.pipe 形式时,我得到了预期的结果(数组中的两个对象都有名称的标签字段和插入在一起的完成字段)

但是,使用传感器形式我得到一个空数组。如果我删除 R.filterR.map(因此管道中只有一个操作),我会得到管道中只有该项目的预期结果。但是,我似乎无法将这两个操作结合起来。

我在这里错过了什么?

有此码的码笔:http://codepen.io/rodeoclash/pen/EWJmMZ?editors=1112

正如this article中指出的:

We needed to change from pipe => compose because of the nature of transducers. Although transducers can be composed directly, the execution of the transformation is reversed. This means any time you would use R.pipe for arrays, you would use R.compose for transducers, and vice-versa.

These articles are also very useful. There is also pretty cool tool for inspecting stuff: ramda-debug.

const transducer = R.compose(
  R.filter(R.propEq('completed', true)),
  R.map((obj) => {
    return {
      label: `${obj.name} (${obj.completed})`,
    }
  })
)

Ramda REPL 中的示例。