Ramda,连接 propOr/pathOr

Ramda, concat with propOr/pathOr

const obj = {
  psets: [...],
  type: {
   psets: [...]
  }
}

想要连接 psets 道具。他们两个可能都不存在。

R.concat(R.pathOr([], ['type','pSets']), R.propOr([], 'pSets'));

**

Uncaught TypeError: function n(r){return 0===arguments.length||w(r)?n:t.apply(this,arguments)} does not have a method named "concat"

我做错了什么?

R.concat 需要数组或字符串,而不是函数。您可以使用 R.converge 为 concat 准备数组。

注意:R.__ 用作传入参数的占位符,您分配给与最后一个参数不同的位置。

const obj = {
  pSets: [1, 2],
  type: {
   pSets: [3, 4]
  }
}

const fn = R.converge(R.concat, [
  R.pathOr([], ['type','pSets']), 
  R.propOr([], 'pSets')]
)

const result = fn(obj)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

另一个使代码更干燥的选项是使用 R.chain 迭代路径,从对象中获取值,并连接它们:

const obj = {
  pSets: [1, 2],
  type: {
   pSets: [3, 4]
  }
}

const fn = R.curry((paths, obj) => R.chain(R.pathOr([], R.__, obj), paths))

const result = fn([['pSets'], ['type','pSets']], obj)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>